Files
python-tests/README.md
T

109 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# python-tests
> Python tool: https://github.com/astral-sh/uv
```shell
uvx pycowsay 'hello world!'
```
```shell
$ echo 'import requests; print(requests.get("https://astral.sh"))' > example.py
$ uv add --script example.py requests
Updated `example.py`
```
```shell
$ uv run example.py
Reading inline script metadata from: example.py
Installed 5 packages in 12ms
<Response [200]>
```
```shell
uv run --python 3.12 https://git.hatter.ink/hatter/python-tests/raw/branch/main/leap_year.py
```
```shell
uv run 'https://script.hatter.ink/@0/show_myip.py'
```
> https://developer.aliyun.com/mirror/pypi/
`~/.pip/pip.conf`
```ini
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
```
`~/.config/uv/uv.toml`
```toml
[[index]]
url = "https://mirrors.aliyun.com/pypi/simple/"
default = true
```
```shell
pip install requests
pip install cryptography
```
----
```shell
PYTHONPATH=./.venv/lib/python3.10/site-packages/ ./show_my_ip.py
```
<br>
`show_myip.py`
```python
#! /usr/bin/env uv run
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "requests>=2.32.5",
# ]
# ///
import requests;
IP_ACTION_URL = "https://hatter.ink/ip/ip.jsonp"
if __name__ == "__main__":
response = requests.get(IP_ACTION_URL, timeout=10)
if response.status_code != 200:
print("[ERROR]", response.status_code)
else:
response_json = response.json()
print(response_json)
print("Your IP is:", response_json['ip'])
```
```shell
./show_myip.py
```
<br>
在 Python 中,print() 函数默认会对输出进行缓存(buffering)。
```python
import time
for i in range(5, 0, -1):
# end="" 让它不换行,flush=True 强制立即刷新缓存
print(f"\rcountdown: {i}", end="", flush=True)
time.sleep(1)
print("\ndone")
```
通过设置环境变量也可以禁止缓存:
```shell
export PYTHONUNBUFFERED=1
```