【问题标题】:os.system("start") error handlingos.system("start") 错误处理
【发布时间】:2017-04-20 16:12:00
【问题描述】:

我要求使用 os 库输入文件名,当按下打开按钮时,它将打开输入的文件,这可行,但如果用户输入一个不存在的文件,它将抛出windows错误,shell中会显示以下内容?

The system cannot find the file ______.

有没有办法在没有 Windows 错误的情况下处理这个问题?就像使用 try 和 except 语句一样。

谢谢

【问题讨论】:

  • 查看os.system的返回值;如果有错误,它应该是非零的。

标签: python python-3.x error-handling operating-system


【解决方案1】:

您可能想要使用subprocess 模块,而不是使用system

您可以调用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 模块here 的文档。

【讨论】:

  • 谢谢,您提供的第一个解决方案效果很好。
【解决方案2】:

除了从您的平台暂停错误之外,我还将寻求一个独立于平台的解决方案。您可以使用os.path.exists 来检查目录或文件是否存在,如果存在则将命令传递给os.system 以打开文件:

if os.path.exists(path):
    os.system(...)
else: 
    # file does not exist 
    ...

我不建议使用os.system,这样真的会让应用程序的安全性变得脆弱。

【讨论】:

    猜你喜欢
    • 2019-01-18
    • 1970-01-01
    • 2015-09-24
    • 2017-09-23
    • 2015-05-02
    • 1970-01-01
    • 2012-02-21
    • 2016-08-18
    • 2016-01-19
    相关资源
    最近更新 更多