我正在使用Python 3.4.3。我想要做的是,将cmd命令的输出存储到变量中,而不将其打印到命令行中。 Here我找到了答案,但它适用于旧版本但适用于3.4.3,变量" var"包含一些随机字符。例如,如果我尝试用命令" dir"来测试它,它会打印出一团糟。
import subprocess
from subprocess import Popen, PIPE
var = subprocess.Popen(COMMAND, stdin = PIPE, stdout = PIPE, stderr = PIPE).communicate()[1]
print(var)
答案 0 :(得分:0)
如果我理解得很好,你只想运行一个外部命令并将输出变为变量。
import subprocess
def foo():
return subprocess.Popen(COMMAND.split(), stdout=subprocess.PIPE).communicate()[0]
从子流程文档:
Replacing /bin/sh shell backquote
---------------------------------
output=`mycmd myarg`
==>
output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
请注意,COMMAND.split()
有点......太棘手了。例如:
var1 = subprocess.Popen(['echo', '"Hey', 'StackOverflow!"'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var1: "Hey StackOverflow!"\n
var2 = subprocess.Popen(['echo', 'Hey StackOverflow!'], stdout=subprocess.PIPE).communicate()[0]
# String contained in var2: Hey StackOverflow!\n
var1 != var2
# True
答案 1 :(得分:0)
subprocess.check_output做你想要的: https://docs.python.org/2/library/subprocess.html#subprocess.check_output