Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Popen.returncode not working in Python?

Tags:

python

I have a price of code which transfers file from server to local machine. However, the directory the user enters may not be always correct. If the user enters the incorrect directory I am trying to show the error. If the returncode is not None I will show the error. But this doesn't work. No matter what the program throws it always go to else part.

#!/usr/bin/python

import subprocess



result = subprocess.Popen(['sshpass', '-p', 'password', 'rsync', '-avz', '--info=progress2', 'username@host_name:/file_name', '/home/zurelsoft/test'], 
                                    stdout=subprocess.PIPE)

if result.returncode != None:
    print "Directory Incorrect"

else:
    print "Done"
    print result
like image 645
user1881957 Avatar asked Dec 24 '12 06:12

user1881957


People also ask

How do I use subprocess Popen in Python?

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle. For more advanced use cases, the underlying Popen interface can be used directly. Run the command described by args. Wait for command to complete, then return a CompletedProcess instance.

What is Returncode in Python?

The returncode() function provides a simple way to get the return code set by the command executed. The command is run in a sub-process and must require no input. For example, suppose you needed to get the return code set by the following python script: import sys sys. exit(4)

How does Python Popen work?

Popen FunctionThe 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.


1 Answers

subprocess.Popen returns an object (result variable in your case). You need to call the poll or the wait method of this object to set the returncode status. Then you can check the result.returncode

See http://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode

The child return code, set by poll() and wait() (and indirectly by communicate()). A None value indicates that the process hasn’t terminated yet.

like image 198
luc Avatar answered Oct 15 '22 03:10

luc