News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

How do I execute a program or call a system command?

posted on 2023-05-03 19:30     read(297)     comment(0)     like(2)     collect(3)


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


solution


Use the subprocess module in the standard library:

import subprocess

# for simple commands
subprocess.run(["ls", "-l"]) 

# for complex commands, with many args, use string + `shell=True`:
cmd_str = "ls -l /tmp | awk '{print $3,$9}' | grep root"
subprocess.run(cmd_str, shell=True)

The advantage of subprocess.run over os.system is that it is more flexible (you can get the stdout, stderr, the "real" status code, better error handling, it is not prone to problems due to spaces in folders in the path to the executable, etc...).

Even the documentation for os.system recommends using subprocess instead:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

On Python 3.4 and earlier, use subprocess.call instead of .run:

subprocess.call(["ls", "-l"])


Category of website: technical article > Q&A

Author:qs

link:http://www.pythonblackhole.com/blog/article/143/feb562ab7e190b998075/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

2 0
collect article
collected

Comment content: (supports up to 255 characters)