python · 1月 15, 2023 0

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()

Instead of.

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

subprocess.call.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.

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

subprocess.run.Similar to the above but even more flexible and returns a CompletedProcess object.

Os.fork, os.exec, os.spawn are similar to their C language counterparts.

%d 博主赞过: