使用 subprocess.call 打开程序 [英] Using subprocess.call to open a program

查看:61
本文介绍了使用 subprocess.call 打开程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an automation program and I'm using subprocess.call to open Google Chrome. The code for this is

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

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

When I run this program through the terminal Chrome launches but it remains tied to the terminal. If I try call('google-chrome &') I get No such file or directory in my traceback. ($ google-chrome & when entered in terminal will launch Chrome but it won't tie it to the terminal).

我也试过 call(['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.

我应该为此使用 subprocess.call 吗?

Should I be using subprocess.call for this?

推荐答案

不要使用 call();它将等待该过程完成.

Don't use call(); it'll wait for the process to complete.

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

Use the subprocess.Popen() class directly, without waiting:

from subprocess import Popen

Popen(['google-chrome'])

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

You can redirect its output to the bit bin, if desired:

from subprocess import Popen, STDOUT
import os

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

如果您想做的只是生成具有给定 URL 的浏览器,请查看 webbrowser 模块;它在后台使用相同的调用在后台生成浏览器进程(包括重定向到 /dev/null).虽然 Google Chrome 没有列在文档页面上,但模块的 2.7.5 源代码确实将 google-chromechrome 列为可识别的浏览器字符串.

If all you want do do is spawn a browser with a given URL, take a look at the webbrowser module; it uses the same call under the hood to spawn a browser process in the background (including the redirection to /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.

这篇关于使用 subprocess.call 打开程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆