如何从python代码调用shell脚本?
当前回答
我正在运行python 3.5, subprocess.call(['./test.sh'])不适合我。
我给出三个解取决于你对输出的处理。
1 -调用脚本。您将在终端中看到输出。输出是一个数字。
import subprocess
output = subprocess.call(['test.sh'])
2 -调用和转储执行和错误到字符串。除非输出(stdout),否则在终端中看不到执行。Shell=True作为Popen中的参数并不适用于我。
import subprocess
from subprocess import Popen, PIPE
session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()
if stderr:
raise Exception("Error "+str(stderr))
3 -调用脚本,将temp.txt的echo命令转储到temp_file中
import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
output = file.read()
print(output)
别忘了看一看doc子流程
其他回答
以防脚本有多个参数
#!/usr/bin/python
import subprocess
output = subprocess.call(["./test.sh","xyz","1234"])
print output
输出将给出状态代码。如果脚本成功运行,它将给出0否则非零整数。
podname=xyz serial=1234
0
下面是test.sh shell脚本。
#!/bin/bash
podname=$1
serial=$2
echo "podname=$podname serial=$serial"
使用@Manoj-Govindan的答案,我发现我可以从python运行简单的shell脚本,但我拼命想要运行的脚本会因为错误而失败
Syntax error: "(" unexpected
我把第一个参数从'sh'改成了'bash',还有viola!突然,它执行了。
subprocess.call(['bash', './test.sh'])
请尝试以下代码:
Import Execute
Execute("zbx_control.sh")
如果您的shell脚本文件没有执行权限,请按照以下方法执行。
import subprocess
subprocess.run(['/bin/bash', './test.sh'])
import os
import sys
假设test.sh是您想要执行的shell脚本
os.system("sh test.sh")
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 查看PS命令的全部输出
- 使用try和。Python中的if