6 ways to call external command in python
In this tutorial, I will list number of the ways (6 at the moment) to call external programs and the advantages and disadvantages of each:
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to
sys.stdin, etc. are not reflected in the environment of the executed command.
- Advantage: This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection.
os.system("some_command < input_file | another_command > output_file")
- You have to manually handle the escaping of shell characters such as spaces
- This also lets you run commands which are simply shell commands and not actually external programs
os.popen(command[, mode[, bufsize]])
Open a pipe to or from command.
- Simple as os.system(command)
- It gives you a file-like object that you can use to access standard input/output for that process.
- If you pass everything as a string, then your command is passed to the shell
- If you pass them as a list then you don’t need to worry about escaping anything
CautionDeprecated since version 2.6: This function is obsolete.
Popen class of the
This is intended as a replacement for
os.popen but has the downside of being slightly more complicated by virtue of being so comprehensive.
with subprocess.Popen(["ifconfig"], stdout=PIPE) as proc: log.write(proc.stdout.read())
call function from the
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None)
Run the command described by args. Wait for command to complete, then return the returncode attribute.
This is basically just like the
Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
ret = subprocess.call("echo Hello 123", shell=True)
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)
Run the command described by args. Wait for command to complete, then return a CompletedProcess instance. This
is a lot like the above but even more flexible and returns a
CompletedProcess object when the command finishes executing.
fork/exec/spawn functions from
Actually, this way is not recommended. The
subprocess module should probably be what you use.