首页 > 解决方案 > Ubuntu:Python3检查文件是否存在子进程

问题描述

我设法在 ubuntu 上使用 python3 安装了基于 Windows 的网络打印机。

为了更好地编码,我想首先检查下载后是否存在包含驱动程序的文件。我知道它是可能的os.path.isfile或类似的东西,但我想用 subprocess 来做到这一点,尽管未来不再支持 os 。

那么我该怎么做呢?使用 subprocess.call 或类似的东西?

标签: python-3.xsubprocess

解决方案


要检查文件是否存在,您最好使用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.)

推荐阅读