import subprocess
def run_win_cmd(cmd):
result = []
process = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in process.stdout:
result.append(line)
errcode = process.returncode
for line in result:
print(line)
if errcode is not None:
raise Exception('cmd %s failed, see above for details', cmd)
新的
subprocess.check_output
和类似的命令应该替换os.system
。有关详细信息,请参见this page。虽然我无法在Windows上对此进行测试(因为我没有访问任何Windows计算机的权限),但以下操作应该有效:check_output
返回命令的输出字符串。或者,subprocess.call
只运行命令并返回命令的状态(如果一切正常,通常为0)。还要注意,在python 3中,字符串输出现在是
bytes
输出。如果你想把它变成一个字符串,你需要如果需要,you can tell it程序输出的编码类型。默认值是
utf-8
,通常工作正常,但其他标准选项是here。还要注意,@bluescorpion在注释中说Windows 10需要一个尾随的反斜杠,如
check_output("dir C:\\", shell=True)
。需要双反斜杠,因为\
是python中的一个特殊字符,所以它必须是escaped。(还要注意,如果\
是字符串的最后一个字符-r"dir C:\"
是语法错误,即使在字符串前面加上r
也没有帮助,尽管r"dir C:\ "
不是。)@srini beerge的答案的重构,得到输出和返回代码
您将使用操作系统模块system method。
您只需输入命令的字符串形式,返回值是windows enrivonment变量COMSPEC
例如:
system('python')打开windows命令提示符并运行python解释器
相关问题 更多 >
编程相关推荐