【问题标题】:Python - subprocess command with pipe which also writes to a filePython - 带有管道的子进程命令,它也写入文件
【发布时间】:2017-09-07 08:15:56
【问题描述】:

我想通过带有 piple 的 python subprocess.call 在 Windows 上运行批处理脚本。我有以下列表,其中包含批处理脚本及其所有参数。

  process_list [ 'batch_script.bat', 'arg1', 'arg2', 'arg3' ]

现在我想使用下面的管道和 grep 命令 grep 几个特定的​​行

above command|grep -iE 'abc|xyz'

现在我也想将它写入文件或存储到变量中,我试图找到一些解决方案,例如stdout=subprocess.PIPE

pipe_var= ' | grep -iE \'abc|xyz\''
process_list.append(pipe_var)
subprocess.call(process_list, stdout=fo, shell=True) or this one
subprocess.call(process_list, stdout=subprocess.PIPE, shell=True)

但它符合我的要求。你能帮忙吗?

【问题讨论】:

  • 我不会使用grep,但python本机正则表达式匹配(你可以避免|shel==True然后
  • 你不应该使用带有 shell=True 的 args 列表,因为子进程不知道如何从 Windows 上的列表构建 shell 命令行(在 Unix 上它甚至更错误,原因不同)。此外,“|” grep 表达式中的字符需要用双引号转义。这可能有效:cmd = 'batch_script.bat "arg1" "arg2" "arg3" | grep -iE "abc|xyz"'。然后为标准输出使用管道,读取它并对输出做任何你想做的事情,包括将其写入文件。

标签: python batch-file subprocess pipe


【解决方案1】:

有一个redirect stdout function

类似的东西:

import sys
sys.stdout = open('file.txt', 'w')
print 'this will now goto file.txt'

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 2019-12-01
    • 1970-01-01
    • 2012-03-21
    • 2017-03-10
    • 1970-01-01
    • 2017-10-15
    • 2021-11-10
    • 1970-01-01
    相关资源
    最近更新 更多