There are lots of different libraries which allow you to call external commands with pythonPython. For each library I've given a description and shown an example of calling an external command, the. The command I used as the example is ls -l
(list all files). If you want to find out more about any of the libraries I've listed and linked the documentation for each of them.
Subprocess allows you to call external commands and connect them to their input/output/error pipes (stdin, stdout, and stderr). Subprocess is the default choice for running commands, but sometimes other modules are better.
subprocess.run(["ls", "-l"]) # runRun command
subprocess.run(["ls", "-l"], stdout=subprocess.PIPE) # thisThis will run the command and return any output
subprocess.run(shlex.split("ls -l")) # youYou can also use the shlex library to split the command
os.system("ls -l") # run command
os.popen("ls -l").read() # thisThis will run the command and return any output
sh is a subprocess interface which lets you call programs as if they were functions, this. This is useful if you want to run a command multiple times.
sh.ls("-l") # runRun command normally
ls_cmd = sh.Command("ls") # saveSave command as a variable
ls_cmd() # runRun command as if it were a function
plumbum is a library for "script-like" pythonPython programs. You can call programs like functions as in shsh
. Plumbum is useful if you want to run a pipeline without the shell.
pexpect lets you spawn child applications, control them and find patterns in their output. This is a better alternative to subprocess for commands that expect a tty on unixUnix.
pexpect.run("ls -l") # runRun command as normal
child = pexpect.spawn('scp foo [email protected]:.') # spawnsSpawns child application
child.expect('Password:') # whenWhen this is the output
child.sendline('mypassword')
fabric is a Python 2.5 and 2.7 library, it. It allows you to execute local and remote shell commands. Fabric is simple alternative for running commands in a secure shell (SSH)
fabric.operations.local('ls -l') # runRun command as normal
fabric.operations.local('ls -l', capture = True) # runRun command and receive output
envoy is known as "subprocess for humans", it. It is used as a convenience wrapper around the subprocess
module.
r = envoy.run("ls -l") # runRun command
r.std_out # get output
commandscommands
contains wrapper functions for os.popen
, but it has been removed from Python 3 since subprocess
is a better alternative.
[EDIT] BasedThe edit was based on J.F. Sebastian's comment.