How to execute a pr...
 
Share:
Notifications
Clear all

How to execute a program or call a system command from Python


Shout4Education
(@shout4education)
New Member
Joined: 11 months ago
Posts: 1
Topic starter  

How do I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?


Quote
Topic Tags
myTechMint
(@mytechmint)
Active Member
Joined: 11 months ago
Posts: 6
 

Use the subprocess module in the standard library.

import subprocess
import sys

command = subprocess.run(['ls', '-l'], capture_output=True)

sys.stdout.buffer.write(command.stdout)
sys.stderr.buffer.write(command.stderr)
sys.exit(command.returncode)

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, 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"])

Neha liked
ReplyQuote