读取命令行输出 Python
Reading Command line output Python
我在使用 python 发出命令然后获取值以创建服务列表时遇到问题。
serviceList = subprocess.Popen(command, shell=True, stdout =subprocess.PIPE).stdout.read()
print serviceList
command
是一个有效的命令,当我将它复制并粘贴到 cmd 中时,它可以完美运行,为我提供服务列表及其状态。
如果我 运行 这个命令它只是 returns 什么都没有。当我打印出 serviceList 时,它是空白的。
我正在使用 python 2.7
要保存标准输出,请将 output = serviceList.stdout.readlines()
添加到您的代码中。
如果程序简单地打印出一堆信息然后退出,一个更简单的方法(也不会因为缓冲区已满而死锁)是调用:
process = subprocess.Popen(command) # only call shell=True if you *really need it
stdoutdata, stderrdata = process.communicate() # blocks until process terminates
*Calling shell=True with external input opens your code to shell injection attacks, and should be used with caution
您必须使用 communicate()
方法而不是 stdout.read()
来获取 serviceList
的值。
甚至 Python 文档也推荐它。
Warning: Use communicate()
rather than .stdin.write
, .stdout.read
or .stderr.read
to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
试试这个:
proc = subprocess.Popen(command, shell=True, stdout =subprocess.PIPE)
serviceList = proc.communicate()[0]
print serviceList
communicate()
returns 一个元组 (stdoutdata, stderrdata)
。在这里,我将元组的第一个元素分配给 serviceList
.
还有子进程函数 check_output() 会阻塞进程,returns 进程输出为字节串。如果你想避免阻塞,你可以创建一个调用它的函数并将它用作新 Thread() 的目标,例如
import subprocess
import threading
def f():
print subprocess.check_output([command])
threading.Thread(target=f).start()
我在使用 python 发出命令然后获取值以创建服务列表时遇到问题。
serviceList = subprocess.Popen(command, shell=True, stdout =subprocess.PIPE).stdout.read()
print serviceList
command
是一个有效的命令,当我将它复制并粘贴到 cmd 中时,它可以完美运行,为我提供服务列表及其状态。
如果我 运行 这个命令它只是 returns 什么都没有。当我打印出 serviceList 时,它是空白的。
我正在使用 python 2.7
要保存标准输出,请将 output = serviceList.stdout.readlines()
添加到您的代码中。
如果程序简单地打印出一堆信息然后退出,一个更简单的方法(也不会因为缓冲区已满而死锁)是调用:
process = subprocess.Popen(command) # only call shell=True if you *really need it
stdoutdata, stderrdata = process.communicate() # blocks until process terminates
*Calling shell=True with external input opens your code to shell injection attacks, and should be used with caution
您必须使用 communicate()
方法而不是 stdout.read()
来获取 serviceList
的值。
甚至 Python 文档也推荐它。
Warning: Use
communicate()
rather than.stdin.write
,.stdout.read
or.stderr.read
to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.
试试这个:
proc = subprocess.Popen(command, shell=True, stdout =subprocess.PIPE)
serviceList = proc.communicate()[0]
print serviceList
communicate()
returns 一个元组 (stdoutdata, stderrdata)
。在这里,我将元组的第一个元素分配给 serviceList
.
还有子进程函数 check_output() 会阻塞进程,returns 进程输出为字节串。如果你想避免阻塞,你可以创建一个调用它的函数并将它用作新 Thread() 的目标,例如
import subprocess
import threading
def f():
print subprocess.check_output([command])
threading.Thread(target=f).start()