Python - open new shell and run command

允我心安 提交于 2019-12-30 10:08:32

问题


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

os.system(cmd)

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

Thanks, Dan


回答1:


I am using the following method (this will also redirect stderr to 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



回答2:


os.system() is deprecated in favour of :

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



回答3:


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

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.



来源:https://stackoverflow.com/questions/12857879/python-open-new-shell-and-run-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!