所以我想从os.popen搬往subprocess.popen所推荐的用户指南。我遇到的唯一困难是我似乎无法找到使readlines()工作的方法。Python子进程readlines()?
所以我曾经是能够做到
list = os.popen('ls -l').readlines()
但我不能做
list = subprocess.Popen(['ls','-l']).readlines()
所以我想从os.popen搬往subprocess.popen所推荐的用户指南。我遇到的唯一困难是我似乎无法找到使readlines()工作的方法。Python子进程readlines()?
所以我曾经是能够做到
list = os.popen('ls -l').readlines()
但我不能做
list = subprocess.Popen(['ls','-l']).readlines()
随着subprocess.Popen
,使用communicate
来读取和写入数据:
out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate()
然后,您总是可以将流程'stdout
中的字符串与分开。
out = out.splitlines()
认为这是意味着是“漂亮的新途径“这样做。感谢您的回答,我会在超时时间到时将其设置。我迷惑不解。 – jdborg
用'communicate'的问题是,你的所有输出的同时,以非递归'ls'的情况下是不太可能有问题。通过使用'stdout'成员,你可以逐行阅读(想想'find')。 –
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.stdout.readlines()
,或者,如果你想读行由行(也许是其他过程比ls
更密集):
for ln in ls.stdout:
# whatever
这种方法比公认的答案更可取,因为它允许在子过程产生输出时通读输出。 – Hoons
Making a system call that returns the stdout output as a string:
lines = subprocess.check_output(['ls', '-l']).splitlines()
使用子的更详细的方式。
# Set the command
command = "ls -l"
# Setup the module object
proc = subprocess.Popen(command,
shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# Communicate the command
stdout_value,stderr_value = proc.communicate()
# Once you have a valid response, split the return output
if stdout_value:
stdout_value = stdout_value.split()
宁愿做'名单= subprocess.call([ 'ls' 的, ' - L'])readlines方法() ' – jdborg
这是不对的 - 'call'只返回返回代码,而不是输出。 – agf
http://stackoverflow.com/questions/2924310/whats-a-good-equivalent-to-pythons-subprocess-check-call-that-returns-the-conte – jfs