【问题标题】:shell pipelines using subprocess.Popen使用 subprocess.Popen 的 shell 管道
【发布时间】:2019-05-20 00:18:15
【问题描述】:

我想在 subprocess.Popen 中使用包含多个管道的命令。这是我的简短脚本

#!/usr/bin/env python 

import subprocess
import datetime
import shlex

todayyearnumber = str(datetime.datetime.now().strftime('%Y'))

command = 'git log --grep "' + todayyearnumber + '.*commit" --oneline'
command2 = 'cut -d " " -f4'

argsplit=shlex.split(command)
argsplit2=shlex.split(command2)

process1=subprocess.Popen(argsplit, cwd=ebb_path, stdout=subprocess.PIPE)

process2=subprocess.Popen(argsplit2, stdin=process1.PIPE, stdout=subprocess.PIPE)

print(process2.stdout.read().decode('utf-8'))

但是,我收到一个错误

Traceback(最近一次调用最后一次): 文件“./proces.py”,第 35 行,在 process2=subprocess.Popen(argsplit2,stdin=process1.PIPE,stdout=subprocess.PIPE) AttributeError:“Popen”对象没有属性“PIPE”

你能帮我解决我的错误吗?

【问题讨论】:

    标签: python-3.x unix process


    【解决方案1】:

    这是因为PIPE 是一个常量,定义为subprocess.PIPE

    如果我理解正确,完整的程序如下所示:

    #!/usr/bin/env python
    
    import subprocess
    import shlex
    
    command = 'echo a b c'
    command2 = "awk '{print $2}'"
    
    argsplit=shlex.split(command)
    argsplit2=shlex.split(command2)
    
    ebb_path="/tmp/"
    process1=subprocess.Popen(argsplit, cwd=ebb_path, stdout=subprocess.PIPE)
    stdout_data, stderr_data = process1.communicate(timeout=1)
    
    process2=subprocess.Popen(argsplit2, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    stdout_data2, _ = process2.communicate(input=stdout_data,
                                        timeout=1)
    
    print(stdout_data2.decode('utf-8'))
    

    【讨论】:

      猜你喜欢
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多