使用subprocess.call打开程序

时间:2013-11-18 16:37:14

标签: python subprocess

我正在编写自动化程序,我正在使用subprocess.call打开Goog​​le Chrome。这个代码是

from subprocess import call
...
call('google-chrome')

当我通过终端运行此程序Chrome启动但它仍然与终端绑定。如果我尝试call('google-chrome &'),我会在追溯中获得No such file or directory。 ($ google-chrome &在终端输入时会启动Chrome,但不会将其绑定到终端。)

我也试过call(['google-chrome', '&']),但这打开Chrome仍然与终端绑在一起,但它认为&是我想要打开的网站的论据。

我应该使用subprocess.call吗?

1 个答案:

答案 0 :(得分:3)

不要使用call();它会等待这个过程完成。

直接使用subprocess.Popen() class,无需等待:

from subprocess import Popen

Popen(['google-chrome'])

如果需要,您可以将其输出重定向到位bin:

from subprocess import Popen, STDOUT
import os

Popen(['google-chrome'], stdout=os.open(os.devnull, os.O_RDWR), stderr=STDOUT)

如果你想做的只是产生一个带有给定URL的浏览器,请看webbrowser module;它使用相同的调用来在后台生成浏览器进程(包括重定向到/dev/null)。虽然文档页面中未列出Google Chrome,但该模块的2.7.5源代码会将google-chromechrome列为已识别的浏览器字符串。

相关问题