Execute the command using the subprocess module. (* Added about subprocess.run () function: 2/15 23:30)
subprocess.call(cmd)
Basic usage.
Just execute the command given as an argument.
If the command execution is successful, 0
is returned.
import subprocess
res = subprocess.call('ls')
#=>Result of ls command
print res
#=>0 if the command is successful
subprocess.check_call(cmd)
Executes the command given as an argument.
If the command execution is successful, 0
is returned.
When it fails, it raises a CalledProcessError exception, so you can handle it with try-except
.
import subprocess
try:
res = subprocess.check_call('dummy')
except:
print "Error."
#=> Error.
If a command that cannot be executed is given, exception handling can be performed.
subprocess.check_output(cmd)
Executes the command given as an argument.
If the command execution is successful, the output is returned.
Like check_call, it raises a CalledProcessError exception when it fails, so you can handle it with try-except
.
import subprocess
try:
res = subprocess.check_output('ls')
except:
print "Error."
print res
#=>Execution result of ls
At this point, you can execute simple commands. Finally, about executing commands with arguments.
subprocess.call(*args)
The same applies to check_call and check_output. Specify commands and arguments by array.
import subprocess
args = ['ls', '-l', '-a']
try:
res = subprocess.check_call(args)
except:
print "Error."
#=> "ls -l -a"Execution result of
subprocess.run(cmd)
(Reflects the comment received from @MiyakoDev)
From Python3.5, the subprocess.run () function that combines the above three commands has been added.
import subprocess
import sys
res = subprocess.run(["ls", "-l", "-a"], stdout=subprocess.PIPE)
sys.stdout.buffer.write(res.stdout)
Sample code to get the output. The output is returned as a ** byte string **.
There were ʻos.systemusing the os module and
commands.getstatusoutput` using the commands module, but they seem to be deprecated now.
Recommended Posts