Friday, January 17, 2025
HomeTechHow 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 a simple example:

python
import subprocess

# Run a system command
result = subprocess.run(['command', 'arg1', 'arg2'], capture_output=True, text=True)

# Print the output
print(result.stdout)

Replace 'command' with the program name and its arguments. The capture_output=True option captures the command’s output, and text=True ensures it’s returned as a string.

For simpler use cases, you can use os.system(command), but subprocess is more powerful and secure. Always validate inputs to avoid security risks like command injection.

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