【问题标题】:piping subprocess output to stdin in python not working在python中管道子进程输出到stdin不起作用
【发布时间】:2019-10-07 15:17:38
【问题描述】:

我想检查一个文件的格式是否正确

command_process = subprocess.Popen('black -q
    file_utils.py'.split(' '), stdout=subprocess.PIPE)

subprocess.run(['diff', '-q', 'file_utils.py'], 
    stdin=command_process.stdout, stdout=subprocess.PIPE, universal_newlines=True)

上面的命令出现以下错误

diff: missing operand after `file_utils.py'
diff: Try `diff --help' for more information.
CompletedProcess(args=['diff', '-q', 'file_utils.py'], returncode=2, stdout='')

【问题讨论】:

  • 不要使用str.split;它不遵循 shell 语法规则。手动构建列表,或使用shlex.split

标签: python subprocess


【解决方案1】:

diff 需要被告知从标准输入中读取。

subprocess.run(['diff', '-q', 'file_utils.py', '-'], 
stdin=command_process.stdout, stdout=subprocess.PIPE, universal_newlines=True)

subprocess.run(['diff', '-q', '-', 'file_utils.py'], 
stdin=command_process.stdout, stdout=subprocess.PIPE, universal_newlines=True)

取决于您想要的顺序。

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 2018-03-11
    • 2016-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2011-06-18
    相关资源
    最近更新 更多