python-3.x - Ubuntu:Python3检查文件是否存在子进程
问题描述
我设法在 ubuntu 上使用 python3 安装了基于 Windows 的网络打印机。
为了更好地编码,我想首先检查下载后是否存在包含驱动程序的文件。我知道它是可能的os.path.isfile
或类似的东西,但我想用 subprocess 来做到这一点,尽管未来不再支持 os 。
那么我该怎么做呢?使用 subprocess.call 或类似的东西?
解决方案
要检查文件是否存在,您最好使用pathlib
,这是与文件系统交互的 Pythonic 和可移植方式。
但是为了避免检查时间到使用时间错误 (TOCTTOU),您应该考虑:
代替 :
if check_printer_present():
# now, after checking the printer is present,
# the printer might go offline
use_printer()
更好的使用:
try:
use_printer()
except PrinterError():
printer_error_cleanup()
看:
https://de.wikipedia.org/wiki/Time-of-Check-to-Time-of-Use-Problem
你可能记得这个成语:
it's better to ask forgiveness than permission
(t is better to act decisively and apologize for it later
than to seek approval to act and risk delay, objections, etc.)
推荐阅读
- excel - 使用 IP 地址保存在网络中时,宏另存为文件名不起作用
- c# - ActiveMQ 带 ssl 证书认证(两种方式)
- javascript - catch and handle connection refused error using Axios
- java - WebSocketListener OnMessage 被阻止并且其他传入消息被排队
- laravel - 如何删除服务器上的“public/index.php”?
- java - apache-commons-csv println 方法不在输出中打印换行符
- python - 是否有类似于 R 的 brglm 的东西来帮助使用 statsmodels Logit 处理 Python 中的准分离?
- http-headers - 如何在 WSO2 APIM 2.6 中使用运行时值设置标头中介值?
- android - AndoridManifest 权限被忽略
- c# - Unity:附加到 DontDestroyOnLoad 对象的子对象的脚本被调用两次