mac自带python与windows编程有什么区别_在Windows和Mac OS中都使用Python中的默认OS应用程序打开文档...

You can also call them via subprocess module, but...

For Python 2.7 and newer, simply use

subprocess.check_call(['open', filename])

In Python 3.5+ you can equivalently use the slightly more complex but also somewhat more versatile

subprocess.run(['open', filename], check=True)

If you need to be compatible all the way back to Python 2.4, you can use subprocess.call() and implement your own error checking:

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

Now, what are the advantages of using subprocess?

Security: In theory, this is more secure, but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpret, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type 'filename ; rm -rf /'" problem, and if the file name can be corrupted, using subprocess.call gives us little additional protection.

Error handling: It doesn't actually give us any more error detection, we're still depending on the retcode in either case; but the behavior to explicitly raise an exception in the case of an error will certainly help you notice if there is a failure (though in some scenarios, a traceback might not at all be more helpful than simply ignoring the error).

Spawns a (non-blocking) subprocess: We don't need to wait for the child process, since we're by problem statement starting a separate process.

To the objection "But subprocess is preferred." However, os.system() is not deprecated, and it's in some sense the simplest tool for this particular job. Conclusion: using os.system() is therefore also a correct answer.

A marked disadvantage is that the Windows start command requires you to pass in shell=True which negates most of the benefits of using subprocess.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值