2017-09-07 84 views
0

我想在窗口上通过python subprocess.call与piple运行批处理脚本。我有下面的列表,其中包含批处理脚本及其所有参数。Python - 子流程命令与管道,也写入文件

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

现在我想用下面的管道和grep命令

above command|grep -iE 'abc|xyz' 

现在我也想将其写入到文件或存储到一个变量到grep几个特定的​​线,我试图找到一些解决方案像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) 

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

+0

我不会用'grep'但python原有的正则表达式匹配这个(你能避免'|'和'SHEL = = True' Then –

+0

你不应该在'shell = True'时使用args列表,因为子进程不知道如何从Windows的列表中建立一个shell命令行(在Unix上它更加错误,原因不同) 。grep表达式中的“|”字符需要用双引号进行转义,这可能会起作用:'cmd ='batch_script.bat“arg1”“arg2”“arg3”| grep -iE“abc | x YZ“''。然后使用管道输出stdout,读取它并根据输出执行任何操作,包括将其写入文件。 – eryksun

回答

0

有一个redirect stdout function

一些接近这一点:

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