我要求使用OS库的文件名进行输入,当按下打开按钮时,它将打开输入的文件,但如果用户输入一个不存在的文件将丢下Windows错误,以下将显示在Shell中?
The system cannot find the file ______.
有没有窗口错误的方法来处理此操作?喜欢尝试尝试和异常语句。
谢谢
而不是使用system
,您可能需要使用subprocess
模块。
您可以致电os.path.isfile
检查文件是否存在,或者您可以提出exception
为:
if os.path.isfile('your_file'):
# If required, you can read your file's output through this way
output = subprocess.Popen(['./your_file'], stdout = subprocess.PIPE)
或,
try:
output = subprocess.Popen(['./your_file'], stdout = subprocess.PIPE)
except FileNotFoundError as e:
print('Oops, file not found')
在此处查看subprocess
模块的文档。
除了暂停您平台上的错误外,我还将寻求平台独立解决方案。您可以使用os.path.exists
检查目录或文件是否存在,如果存在,则将命令传递给os.system
以打开文件:
if os.path.exists(path):
os.system(...)
else:
# file does not exist
...
我不建议使用os.system
,您确实以这种方式使应用程序的安全性。