【发布时间】:2013-10-24 03:08:48
【问题描述】:
我需要使用 python 在特定应用程序中打开一个文件。我将默认使用默认的应用程序位置/文件名打开文件;但是,如果应用程序无法打开,我想处理该错误并为用户提供一些其他选项。
到目前为止,我已经明白 subprocess.call 是最好的方法,而不是 system.os
应用程序:/Applications/GreatApp.app
这很好用
subprocess.call(['open','/Applications/GreatApp.app','placeholder.gap'])
但是,当我开始添加 try / except 循环时,它们似乎什么也没做。 (注意应用程序名称中的空格 - 我使用了错误的名称来强制异常)
try:
subprocess.call(['open','/Applications/Great App.app','placeholder.gap'])
except:
print 'this is an error placeholder'
我仍然会在 python 中看到以下错误提示
The file /Applications/Great App.app does not exist.
我发现的最接近某种形式的错误处理如下。看看 retcode 的价值是解决这个问题的正确方法吗?
try:
retcode = subprocess.call("open " + filename, shell=True)
if retcode < 0:
print >>sys.stderr, "Child was terminated by signal", -retcode
else:
print >>sys.stderr, "Child returned", retcode
except OSError, e:
print >>sys.stderr, "Execution failed:", e
结果证明 retcode 不是办法,因为正确和错误的名称都会给出大于 0 的值。
【问题讨论】:
-
是的,retcode 方法是正确的。也许尝试将最终代码 sn-p 中的
subprocess.call参数与第一个参数交换?shell=True产生一定程度的间接性,在这种情况下应该是不必要的,因为open不是 shell 命令。 -
感谢您的确认 - 我更深入地研究并发现将 if retcode
-
subprocess.call()的args参数中的第一项不应该是应用程序吗? -
retcode(或退出状态码)如果非零则表示错误,如果等于0则表示成功。我相信错误值通常在 1-255 之间。
标签: python file error-handling subprocess