Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, subprocess, call(), check_call and returncode to find if a command exists

Tags:

I've figured out how to use call() to get my python script to run a command:

import subprocess

mycommandline = ['lumberjack', '-sleep all night', '-work all day']
subprocess.call(mycommandline)

This works but there's a problem, what if users don't have lumberjack in their command path? It would work if lumberjack was put in the same directory as the python script, but how does the script know it should look for lumberjack? I figured if there was a command-not-found error then lumberjack wouldn't be in the command path, the script could try to figure out what its directory is and look for lumberjack there and finally warn the user to copy lumberjack into one of those two places if it wasn't found in either one. How do I find out what the error message is? I read that check_call() can return an error message and something about a returncode attribute. I couldn't find examples on how to use check_call() and returncode, what the message would be or how I could tell if the message is command-not-found.

Am I even going about this the right way?

like image 383
Dave Brunker Avatar asked Dec 31 '12 23:12

Dave Brunker


People also ask

How to use subprocess function check_call() in Python?

Subprocess function check_call() in Python. This function runs the command(s) with the given arguments and waits for it to complete. Then it takes the return value of the code. If it is zero, it returns. Or else it raises CalledProcessError. Its syntax is. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

How to get the exit status code of a subprocess in Python?

Current Article Python 3: Get and Check Exit Status Code (Return Code) from subprocess.run () When running a command using subprocess.run (), the exit status code of the command is available as the .returncode property in the CompletedProcess object returned by run ():

How to run an external process from Python code?

By incorporating the subprocess module, you can easily run external processes directly from your Python code. The Popen, communicate, and returncode methods are the most important functions in this article. Python technique popen () establishes a connection to or from a command.

What is the use of call() function in Python?

Call () function in Subprocess Python This function can be used to run an external command without disturbing it, wait till the execution is completed, and then return the output.


1 Answers

A simple snippet:

try:
    subprocess.check_call(['executable'])
except subprocess.CalledProcessError:
    pass # handle errors in the called executable
except OSError:
    pass # executable not found
like image 50
tzelleke Avatar answered Sep 20 '22 17:09

tzelleke