在Python中调用Bash命令,你可以使用`subprocess`模块。以下是一些示例代码,展示了如何使用`subprocess`模块执行Bash命令和脚本:
示例1:执行Bash命令
import subprocess
定义要执行的bash命令
command = "ls -l"
使用subprocess.run()执行命令,capture_output设置为True
result = subprocess.run(command, shell=True, capture_output=True, text=True)
打印命令执行结果
print(result.stdout)
示例2:执行Bash脚本
import subprocess
脚本路径
script_path = "your_script.sh"
使用subprocess运行脚本
subprocess.run(["bash", script_path])
示例3:传递参数给Bash脚本
import subprocess
定义要执行的bash命令和参数
command = "sh ./test.sh"
args = ["arg1", "arg2"]
使用subprocess.run()执行命令,并将参数作为列表传递
result = subprocess.run(command, shell=True, args=args, capture_output=True, text=True)
打印命令执行结果
print(result.stdout)
注意事项
当使用`shell=True`时,命令字符串应该被当作一个整体来处理,这可能会增加安全风险,特别是当命令字符串来自不可信的源时。
如果你的命令或脚本需要交互式输入,那么使用`shell=True`可能不是最佳选择。
在传递参数时,推荐使用列表形式,这样更加安全和高效。