【发布时间】: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