Python - 打开新的 shell 并运行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12857879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:01:20  来源:igfitidea点击:

Python - open new shell and run command

pythonshellterminalcommand

提问by Dan

At the moment I am running a bash command from within Python using the following method:

目前,我正在使用以下方法从 Python 中运行 bash 命令:

os.system(cmd)

However I need to run the command in a new shell/terminal. Does anyone know how to do this?

但是我需要在新的 shell/终端中运行命令。有谁知道如何做到这一点?

Thanks, Dan

谢谢,丹

回答by Gilles Quenot

os.system()is deprecated in favour of :

os.system()不赞成使用:

import subprocess
print subprocess.check_output("command", shell=True)

回答by pmod

I am using the following method (this will also redirect stderr to stdout):

我正在使用以下方法(这也会将 stderr 重定向到 stdout):

import subprocess    
cmd_line = "echo Hello!"
p = subprocess.Popen(cmd_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out = p.communicate()[0]
print out

回答by H.C.Chen

Windows "WshShell", Google it, is the answer. My complete steps:

Windows“WshShell”,谷歌它,就是答案。我的完整步骤:

Install

安装

1. pip install pywin32-221-cp36-cp36m-win_amd64.whl
2. python.exe pywin32_postinstall.py -install  (DOS command line)

Run

3. import win32com.client
4. WshShell = win32com.client.Dispatch("WScript.Shell")
5. WshShell.run("cmd") 

WshShell.run() is what you need, there are many different ways to run. hidden window, new window, full screen, minimized, ... etc.

WshShell.run() 正是你所需要的,有很多不同的运行方式。隐藏窗口、新窗口、全屏、最小化等。