Wednesday, January 29, 2025
HomeProgrammingHow Do I Execute a Program or Call a System Command?

How Do I Execute a Program or Call a System Command?

In Python, you can execute a program or call a system command using the subprocess module. Here’s an example:

python
import subprocess

# Execute a system command
subprocess.run(["command", "arg1", "arg2"])

For instance, to list files in a directory:

python
subprocess.run(["ls", "-l"]) # Linux/Mac
subprocess.run(["dir"], shell=True) # Windows

Use shell=True for complex commands but avoid it for untrusted input to prevent security risks. If you need to capture the command’s output, use subprocess.run with capture_output=True:

python
result = subprocess.run(["command"], capture_output=True, text=True)
print(result.stdout)
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x