I have the following python code:
try:
subprocess.check_output('service uwsgi stop;pkill -f uwsgi', shell = True)
except:
sys.exit(0)
it should return always 0 but when I run it, it prints 'Terminated' and then I receive a non-zero return code.
Right now, sys.exit(0) will only be called when an exception is raised. To ensure that it is called every time, add a finally statement:
try:
subprocess.check_output('service uwsgi stop;pkill -f uwsgi', shell = True)
except:
# Handle the exception
finally:
sys.exit(0)
Related
Before I run my python script I need to check if an external program is running and wait for it to finish.
I have a few pieces but am having some difficulty putting it all together into a cohesive script.
I can use the following to get the PID of a program and a while loop which will timeout in 10 seconds
from subprocess import check_output
import time
def get_pid(name):
return check_output(["pidof",name])
print "%s" % get_pid("java")
timeout = time.time() + 10
test = 0
while True:
if time.time() > timeout:
print "exception goes here"
break
test = test + 1
time.sleep(1)
If the program is not running get_pid would fail and I think I need to catch the exception in that case? This is where I am not certain where to go. Maybe there is a better way to approach this?
==============
Here is an update which seems to work correctly.
from subprocess import check_output, CalledProcessError
import time
def get_pid(name):
try:
process_status = check_output(["pidof",name])
except CalledProcessError as e:
process_status = None
return process_status
timeout = time.time() + 10
program = "java"
while get_pid(program) != None:
time.sleep(1)
print "1 second loop"
if time.time() > timeout:
raise ValueError ('Timeout exceeded')
print "%s is not running" % program
You can try catching this exception. Because when check_output returns non zero exception instance of CalledProcessError is raised which can be handled. Like this.
from subprocess import CalledProcessError
def get_pid(name):
try:
process_status = check_output(["pidof",name])
except CalledProcessError as e:
process_status = None # You can additionally get return code in the returncode attribute and any output in the output attribute.
return process_status
Hope it works!
Have you tried using the try and except block?
E.g.
try:
#some code
except (RuntimeError, TypeError, NameError):
#pass etc.
You can read the docs here Handling Exceptions
Exception handling can be at the place where the exception is thrown. So if check_output is throwing exception, you could handle below way,
def get_pid(name):
pid_ = None
try:
pid_ = check_output(["pidof",name])
except:
pass
return pid_
#logic to wait for pid_ to finish if found
How can I get the exist status (if command succeed or not) of any line in Python?
For example in bash, $? will tell me the last exist status of any command.
I need it to know if my connection to FTP server was successful or not.
Have you tried using a try/catch? If there was an error while executing the command, an exception will be raised. You can retrieve it with the sys module.
Example code:
import sys
try:
run_command()
except:
e = sys.exc_info()[0]
print(e)
If it is a function you call, it should have a retrun code you can collect like
retVal = doSomething()
Then you can check what happened.
I want to exit Python if I encounter an exception in my function if that function is being executed from the command line, but want to raise an exception and print a stack trace if the my function is not run from the command line.
Right now I have
try:
#...
except Exception as e:
print('ERROR: Some useful message')
if __name__ == '__main__':
raise SystemExit
else:
raise e
but I feel like I'm either doing too much here, or too little.
Is there an idiomatic way to get a stack trace with the original exception when my function is run from the command line; but simply exit if it is being run from the command line?
The better way would be to do this:
import sys
def func():
do_actual_processing()
if not successful:
raise Exception("Yadayada")
if __name__ == '__main__'
try:
func()
except Exception as e:
sys.exit(1)
That is, the function itself does not need to be concerned with whether or not it is run from command line.
I'm currently converting a shell script to python and I'm having a problem. The current script uses the results of the last ran command like so.
if [ $? -eq 0 ];
then
testPassed=$TRUE
else
testPassed=$FALSE
fi
I have the if statement converted over just not sure about the $? part. As I am new to python I'm wondering if there is a similar way to do this?
You should look into the subprocess module for that. There is a check_call method for looking into exit codes (this is one method, there are others as well). As the manual mentions:
Run command with arguments. Wait for command to complete. If the
return code was zero then return, otherwise raise CalledProcessError.
The CalledProcessError object will have the return code in the
returncode attribute
An example of this is:
import subprocess
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command)
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
This will also include output, which you can either redirect to a file or suppress like so:
import subprocess
import os
command=["ls", "-l"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
Here is an example of a call with a non-zero exit code:
import subprocess
import os
command=["grep", "mystring", "/home/cwgem/testdir/test.txt"]
try:
exit_code=subprocess.check_call(command, stdout=open(os.devnull, "w"))
# Do something for successful execution here
print("Program run")
except subprocess.CalledProcessError as e:
print "Program exited with exit code", e.returncode
# Do something for error here
Output:
$ python process_exitcode_test.py
Program exited with exit code 1
Which is captured as an exception that you can handle as above. Note that this will not handle exceptions such as access denied or file not found. You will need to handle them on your own.
You might want use the sh module. It makes shell scripting in Python much more pleasant:
import sh
try:
output = sh.ls('/some/nen-existant/folder')
testPassed = True
except ErrorReturnCode:
testPassed = False
I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.
I hope this is enough information; let me know if more details are required to help me.
Are you just looking for the exit() function?
import sys
if 1 < 0:
print >> sys.stderr, "Something is seriously wrong."
sys.exit(1)
The (optional) parameter of exit() is the return code the script will return to the shell. Usually values different than 0 signal an error.
You can use sys.exit() to exit. However, if any code higher up catches the SystemExit exception, it won't exit.
You can raise exceptions to identify error conditions. Your top-level code can catch those exceptions and handle them appropriately. You can use sys.exit to exit. E.g., in Python 2.x:
import sys
class CameraInitializationError(StandardError):
pass
def camera_test_1():
pass
def camera_test_2():
raise CameraInitializationError('Failed to initialize camera')
if __name__ == '__main__':
try:
camera_test_1()
camera_test_2()
print 'Camera successfully initialized'
except CameraInitializationError, e:
print >>sys.stderr, 'ERROR: %s' % e
sys.exit(1)
You want to check the return code from the c++ program you are running, and exit if it indicates failure. In the code below, /bin/false and /bin/true are programs that exit with error and success codes, respectively. Replace them with your own program.
import os
import sys
status = os.system('/bin/true')
if status != 0:
# Failure occurred, exit.
print 'true returned error'
sys.exit(1)
status = os.system('/bin/false')
if status != 0:
# Failure occurred, exit.
print 'false returned error'
sys.exit(1)
This assumes that the program you're running exits with zero on success, nonzero on failure.