简体   繁体   English

使用subprocess.call打开程序

[英]Using subprocess.call to open a program

I'm writing an automation program and I'm using subprocess.call to open Google Chrome. 我正在编写一个自动化程序,并且正在使用subprocess.call打开Goog​​le Chrome。 The code for this is 的代码是

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

When I run this program through the terminal Chrome launches but it remains tied to the terminal. 当我通过终端运行该程序时,Chrome会启动,但仍与终端绑定。 If I try call('google-chrome &') I get No such file or directory in my traceback. 如果我尝试call('google-chrome &') ,则回溯中No such file or directory得到No such file or directory ( $ google-chrome & when entered in terminal will launch Chrome but it won't tie it to the terminal). $ google-chrome &在终端输入后会启动Chrome,但不会将其绑定到终端)。

I've also tried call(['google-chrome', '&']) but this opens Chrome still tied to the terminal but it thinks the & is an argument for a website I want to open. 我也尝试过call(['google-chrome', '&'])但这会打开Chrome并仍然与终端绑定,但它认为&是我要打开的网站的参数。

Should I be using subprocess.call for this? 我应该为此使用subprocess.call吗?

Don't use call() ; 不要使用call() ; it'll wait for the process to complete. 它将等待该过程完成。

Use the subprocess.Popen() class directly, without waiting: 直接使用subprocess.Popen() ,无需等待:

from subprocess import Popen

Popen(['google-chrome'])

You can redirect its output to the bit bin, if desired: 如果需要,可以将其输出重定向到位bin:

from subprocess import Popen, STDOUT
import os

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

If all you want do do is spawn a browser with a given URL, take a look at the webbrowser module ; 如果您要做的只是使用给定的URL生成浏览器,请看一下webbrowser模块 it uses the same call under the hood to spawn a browser process in the background (including the redirection to /dev/null ). 它在后台使用相同的调用在后台生成浏览器进程(包括重定向到/dev/null )。 Although Google Chrome is not listed on the documentation page, the 2.7.5 source code of the module does list google-chrome and chrome as recognized browser strings. 尽管文档页面上未列出Google Chrome,但该模块的2.7.5源代码确实将google-chromechrome列为可识别的浏览器字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM