【问题标题】:Python subprocess readlines()?Python子进程readlines()?
【发布时间】:2011-11-20 02:03:35
【问题描述】:

所以我正在尝试按照用户指南的建议从 os.popen 转移到 subprocess.popen。我遇到的唯一麻烦是我似乎找不到使 readlines() 工作的方法。

原来我能做到

list = os.popen('ls -l').readlines()

但我做不到

list = subprocess.Popen(['ls','-l']).readlines()

【问题讨论】:

标签: python subprocess


【解决方案1】:
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.stdout.readlines()

或者,如果您想逐行阅读(也许其他进程比ls 更密集):

for ln in ls.stdout:
    # whatever

【讨论】:

  • 这种方法比公认的答案更可取,因为它允许在子进程生成输出时通读输出。
【解决方案2】:

使用subprocess.Popen,使用communicate读写数据:

out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() 

然后您可以随时将字符串从进程的stdout 拆分为splitlines()

out = out.splitlines()

【讨论】:

  • 认为这是一种“不错的新方法”。感谢您的回答,我会在超时时设置它。我只是坚持 popen。
  • communicate 的问题在于您一次获得所有输出,这在非递归ls 的情况下可能不是问题。通过使用stdout 成员,您可以逐行阅读(想想find)。
  • @FredFoo 没错...我创建了一个小线程here 以尝试解决您在评论中提到的问题...虽然它还没有很好地工作:)
【解决方案3】:

Making a system call that returns the stdout output as a string:

lines = subprocess.check_output(['ls', '-l']).splitlines()

【讨论】:

  • 很好,我猜它并不广为人知,因为它只是 Python 2.7+。
  • @agf:点击链接,这里有旧 Python 版本的改编版本。
  • 我知道,我已经关注了您发布的两个链接(并为每个帖子点赞)。我很惊讶直到我看到它是 2.7+ 时才知道这个便利功能。
  • 这个是推荐的解决方案,如果你使用的是2.7+
【解决方案4】:
list = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0].splitlines()

直接来自help(subprocess)

【讨论】:

  • 这不是行列表,它是一个多行字符串。
【解决方案5】:

更详细的子流程使用方式。

# 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()

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2010-11-17
    • 2014-07-04
    相关资源
    最近更新 更多