簡體   English   中英

在子進程中執行cat命令,python的Popen()

[英]execute cat command in subprocess,Popen() of python

如果我在命令下運行,那么python返回了很好的結果..

result_aftermatch= subp.Popen('ls -lrt', stdout=subp.PIPE,stderr=subp.PIPE,shell=True)

但同樣的方式我要求使用代碼從文件greping行如下...

list_of_id=[23,34,56,77,88]
result_aftermatch= subp.Popen('egrep','list_of_IDs','/home/bimlesh/python/result.log', stdout=subp.PIPE,stderr=subp.PIPE,shell=True)
result_lines,result_err= result_aftermatch.communicate()
print result_lines

上面的代碼給出了如下錯誤...

Traceback (most recent call last):
  File "test.py", line 144, in <module>
    result_aftermatch= subp.Popen('egrep','list_of_IDs','/home/bimlesh/python/result.log', stdout=subp.PIPE,stderr=subp.PIPE,shell=True)
  File "/usr/lib/python2.6/subprocess.py", line 573, in __init__
    raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer

請幫忙。

問題是你將命令作為多個args傳遞。 您需要將它們作為列表或元組傳遞。

喜歡:

subp.Popen([ 'egrep','list_of_IDs','/home/bimlesh/python/result.log' ], stdout=subp.PIPE,stderr=subp.PIPE,shell=True)

我猜你正在尋找這個:

list_of_id = [23,34,56,77,88]
ids_regex = '|'.join([str(i) for i in list_of_id])
result_aftermatch = subp.Popen(['egrep', ids_regex, '/home/bimlesh/python/result.log'], stdout=subp.PIPE, stderr=subp.PIPE)
result_lines, result_err = result_aftermatch.communicate()
print result_lines

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM