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?
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)
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 ():
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.
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.
A simple snippet:
try:
subprocess.check_call(['executable'])
except subprocess.CalledProcessError:
pass # handle errors in the called executable
except OSError:
pass # executable not found
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With