Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popen.communicate() returns (None, None) even if script print results

Tags:

python

shell

I have problem with Popen.communicate().

I have script which return string.

Then I have wrote second script which takes that variable.

v = "./myscript arg1 arg2"
com = subprocess.Popen(v, shell=True).communicate()
print com

com returns (None, None). The point is that I can print inside first script the results, shell print result as well. I can't just assign that print to variable.

Of course first script returns value, not print it.

like image 806
Paweł Jaworowski Avatar asked Jan 12 '15 15:01

Paweł Jaworowski


People also ask

What does Popen communicate do?

. communicate() writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.

What does Popen return Python?

Returned value If successful, popen() returns a pointer to an open stream that can be used to read or write to a pipe. If unsuccessful, popen() returns a NULL pointer and sets errno to one of the following values: Error Code. Description.

What does subprocess Popen return?

Popen Function The function should return a pointer to a stream that may be used to read from or write to the pipe while also creating a pipe between the calling application and the executed command. Immediately after starting, the Popen function returns data, and it does not wait for the subprocess to finish.

How does Popen work 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.


1 Answers

From the docs:

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Hence, create the Popen object with:

subprocess.Popen("./myscript arg1 arg2", shell=True,
                 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
like image 124
Aran-Fey Avatar answered Oct 11 '22 09:10

Aran-Fey