# How do I call an external command within Python as if I had typed it in a shell or command prompt?

Here is a summary of ways to call external programs.

Os.system passes the command and arguments.This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection.For example:

os.system("some_command < input_file | another_command > output_file")


However, while this is convenient, you have to manually handle the escaping of shell characters .On the other hand, this also lets you run commands which are simply shell commands .

Os.popen will give you a file-like object that you can use to access standard input/output for that process.There are 3 other variants of popen slightly differently.If you pass them as a list then you don’t need to worry about escaping anything.

print(os.popen("ls -l").read())


subprocess.Popen.This is intended as a replacement for os.popen, but has the downside of being slightly more complicated.

print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()


print os.popen("echo Hello World").read()

return_code = subprocess.call("echo Hello World", shell=True)