Python 运行 命令和捕获结果 - 不要将结果打印到屏幕
Python run command and capture result - do not print result to screen
我正在尝试 运行 来自 python 脚本的命令,但我想存储命令产生的输出,然后检查它的子字符串,但它似乎不是存储在我的变量中,因为它仍然打印到屏幕上。
到目前为止我有这个...
myfile = 'filename.txt'
result = subprocess.Popen(['myprogram.exe', '-f' + myfile], stdout=subprocess.PIPE).communicate()[0]
if result.find("error executing") != -1:
print "error!"
else:
print "success!"
我是 Python 的新手。任何人都可以阐明为什么当我 运行 这个脚本时,myprogram.exe 确实执行了,但它的输出仍然发送到屏幕。如果我打印结果变量,它确实有来自 myprogram.exe 的额外输出,但我也需要显示错误的行。
您只是在重定向标准输出。看起来您的程序向 stderr 输出错误(正如预期的那样),将 stderr=subprocess.PIPE
添加到 Popen
调用。
我正在尝试 运行 来自 python 脚本的命令,但我想存储命令产生的输出,然后检查它的子字符串,但它似乎不是存储在我的变量中,因为它仍然打印到屏幕上。
到目前为止我有这个...
myfile = 'filename.txt'
result = subprocess.Popen(['myprogram.exe', '-f' + myfile], stdout=subprocess.PIPE).communicate()[0]
if result.find("error executing") != -1:
print "error!"
else:
print "success!"
我是 Python 的新手。任何人都可以阐明为什么当我 运行 这个脚本时,myprogram.exe 确实执行了,但它的输出仍然发送到屏幕。如果我打印结果变量,它确实有来自 myprogram.exe 的额外输出,但我也需要显示错误的行。
您只是在重定向标准输出。看起来您的程序向 stderr 输出错误(正如预期的那样),将 stderr=subprocess.PIPE
添加到 Popen
调用。