我想在Python
中使用子进程模块运行一个命令,并将输出存储在变量中。但是,我不希望命令的输出被打印到终端上。
对于以下代码:
def storels():
a = subprocess.Popen("ls",shell=True)
storels()
我在终端中获取了目录列表,但并没有将其存储在a
中。我也尝试过:
def storels():
subprocess.Popen("ls > tmp",shell=True)
a = open("./tmp")
[Rest of Code]
storels()
这也会将ls的输出打印到我的终端。我甚至尝试过使用稍微有些过时的os.system方法执行此命令,因为在终端中运行ls > tmp
并不会将ls
打印到终端上,而是存储在tmp
中。但是,同样的事情发生了。
编辑:
按照marcog的建议后,当运行更复杂的命令时,我遇到了以下错误:cdrecord --help
。Python输出如下:
Traceback (most recent call last):
File "./install.py", line 52, in <module>
burntrack2("hi")
File "./install.py", line 46, in burntrack2
a = subprocess.Popen("cdrecord --help",stdout = subprocess.PIPE)
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
shell=true
。http://docs.python.org/2/library/subprocess.html#frequently-used-arguments - SamHuckabyhttps://dev59.com/P2025IYBdhLWcg3wW0kc#75175057
。 - henrry