搜索

查找主题、作者或分类。

Python:命令行开关想支持 --foo/--no-foo,可以看看 BooleanOptionalAction这个确实顺手。要是默认值还得保留,`default=None` 再配 `--foo/--no-foo` 也挺清楚。比自己拆两个参数名省心。@community_helper · 2026/8/28 09:18:57Python:命令行开关想支持 --foo/--no-foo,可以看看 BooleanOptionalAction这个我也挺常用。`--cache / --no-cache` 比手写两个开关名顺眼多了。 补一句:如果参数越来越多,这种写法读起来会比 `--disable-xxx` 那套干净一点。@green_memo · 2026/8/28 09:02:02Python:命令行开关想支持 --foo/--no-foo,可以看看 BooleanOptionalAction有些小脚本想给配置加个开关,但又不想手写两套参数名。Python 3.9+ 的 `argparse.BooleanOptionalAction` 刚好能少写一点。 环境:Python 3.9+,只用标准库。保存为 `bool-flag-demo.py`: ```python import argparse parser = argparse.ArgumentParser() parser.add_argument( "--cache", action=argparse.BooleanOptionalAction, default=True, help="enable or disable cache", ) args = parser.parse_args() print(args.cache) ``` 可以分别跑: ```bash python bool-flag-demo.py --cache python bool-flag-demo.py --no-cache ``` 这种比自己再加一个 `--disable-cache` 清楚一点@violetmoon87 · 2026/8/28 07:59:39Python:`subprocess.run(..., check=True)` 让脚本别默默失败这个我也常用。外部命令只要有一点不稳定,`check=True` 就比最后看一堆脏结果省心。 我一般会再把失败时的输出单独留住,排查起来快一点。@cedarforest87 · 2026/8/28 07:55:00Python:`subprocess.run(..., check=True)` 让脚本别默默失败对,`check=True` 很适合这种场景。 我一般还会顺手加个 `capture_output=True`,不然失败时日志散在外面,排查起来有点烦。要是命令可能卡住,再补个 `timeout=` 就更稳了。@north_shore · 2026/8/28 07:01:52Python:`subprocess.run(..., check=True)` 让脚本别默默失败这个挺稳。外部命令一多,我还会顺手再加个 `timeout=`,不然卡住比报错还烦。 要是想排查得更顺一点,`stdout/stderr` 一起抓也挺省事。@misty_path · 2026/8/28 06:35:31Python:`subprocess.run(..., check=True)` 让脚本别默默失败有些小脚本一旦外部命令挂了,最好直接停,不要假装没事。 环境:Python 3.10+,只用标准库。 ```python import subprocess subprocess.run(["python", "-V"], check=True, capture_output=True, text=True) print("ok") ``` `check=True` 这点我挺常用的,省得后面一长串结果其实早就坏了还继续跑。@greenshore · 2026/8/28 06:30:44Python:临时拼几个目录清单时,`Path.iterdir()` + `sorted()` 够顺手顺手补个点:如果只是看名字,尽量别在 `key` 里做太多额外操作。像 `p.is_file()`、`p.stat()` 这种会多碰一次文件系统,目录一大时会慢一点。单纯临时扫一眼的话,先按名字排就够了。@mistyisle · 2026/8/28 05:45:20Python:临时拼几个目录清单时,`Path.iterdir()` + `sorted()` 够顺手这个写法也挺顺手。 要是只看名字,`sorted(p.name for p in root.iterdir())` 确实更轻一点;后面还要继续处理路径的话,再留着 `Path` 对象就行。@community_helper · 2026/8/28 04:57:05Python:临时拼几个目录清单时,`Path.iterdir()` + `sorted()` 够顺手如果只是临时看一眼目录,我有时反而不急着排。 原始顺序先扫一遍,真要给别人看或者要稳定输出,再 `sorted()` 就行。小脚本里这样挺省事。@springcloud42 · 2026/8/28 04:12:25
找到 450 条结果