Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute cat command in subprocess,Popen() of python

Tags:

python

If i am running below command then python is returning great result..

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

but in the same way i have requirement of greping lines from file with Code is as below...

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

Above code is giving error as below...

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

Please help.

like image 734
bimlesh sharma Avatar asked Jun 10 '13 19:06

bimlesh sharma


People also ask

How do you run a command in subprocess in Python?

Python Subprocess Run Function run() function was added in Python 3.5 and it is recommended to use the run() function to execute the shell commands in the python program. The args argument in the subprocess. run() function takes the shell command and returns an object of CompletedProcess in Python.

What is Popen command?

The popen() function executes the command specified by the string command. It creates a pipe between the calling program and the executed command, and returns a pointer to a stream that can be used to either read from or write to the pipe.

What is Popen in Python?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.

How does subprocess Popen work?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.


1 Answers

The problem is that you're passing the command as multiple args. You need to pass them as a list or a tuple.

Like:

subp.Popen([ 'egrep','list_of_IDs','/home/bimlesh/python/result.log' ], stdout=subp.PIPE,stderr=subp.PIPE,shell=True)
like image 124
shx2 Avatar answered Oct 15 '22 02:10

shx2