How to execute shell commands in Python

In Python, you can use the subprocess module to call shell commands. Here is a simple example code:

import subprocess

# 执行一个简单的shell命令
subprocess.call('ls')

# 传递参数给shell命令
subprocess.call('echo Hello, World!', shell=True)

# 保存shell命令的输出
output = subprocess.check_output('ls')
print(output.decode('utf-8'))

In the example above, the subprocess.call function can execute a shell command and return the command’s exit status code. The subprocess.check_output function is used to execute a shell command and return its output. It is important to note that the parameters for both subprocess.call and subprocess.check_output functions should be in the form of a string for the shell command. If the command contains spaces or special characters, the shell=True parameter can be set.

Leave a Reply 0

Your email address will not be published. Required fields are marked *