Run unix command on python

Execute the command using the subprocess module. (* Added about subprocess.run () function: 2/15 23:30)

Execute a command

subprocess.call(cmd)

Basic usage. Just execute the command given as an argument. If the command execution is successful, 0 is returned.

</ i> Sample

import subprocess
res = subprocess.call('ls')
#=>Result of ls command
print res
#=>0 if the command is successful

Execute command (if it fails, raise CalledProcessError)

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.

</ i> Sample

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.

Run the command and get its output

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.

</ i> Sample

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.

Execute the command with arguments

subprocess.call(*args)

The same applies to check_call and check_output. Specify commands and arguments by array.

</ i> Sample


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.

</ i> Sample

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 **.

</ i> Reference

There were ʻos.systemusing the os module andcommands.getstatusoutput` using the commands module, but they seem to be deprecated now.

Recommended Posts