深度阅读

How to run bash script in Python?

作者
作者
2023年08月22日
更新时间
12.23 分钟
阅读时间
0
阅读量

To run a Bash script in Python, you can use the subprocess module which allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. Here’s an example:

import subprocess

script_path = '/path/to/script.sh'
result = subprocess.run(script_path, shell=True, stdout=subprocess.PIPE)
output = result.stdout.decode('utf-8')
print(output)

In this example, script_path refers to the full path of the Bash script file. The subprocess.run() function runs the script file as a new process with the shell parameter set to True to indicate that the command is a shell command. The stdout parameter is set to subprocess.PIPE to capture the output of the process, which is returned as a bytes object. Finally, the decode() method is used to convert the output to a string.

Note that the subprocess module can also be used to run other types of commands or executables. The subprocess.run() function returns a CompletedProcess object, which contains information about the completed process, including its return code, stdout, and stderr.

Also, use caution when running shell scripts within Python as it can pose security risks if not implemented properly.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。