如何从python代码调用shell脚本?
当前回答
为了在python脚本中运行shell脚本,并从ubuntu中的特定路径运行它,请使用下面的方法;
import subprocess
a= subprocess.call(['./dnstest.sh'], cwd = "/home/test")
print(a)
CWD是当前工作目录
下图将不能在Ubuntu中运行;这里我们需要删除'sh'
subprocess.call(['sh' ,'./dnstest.sh'], cwd = "/home/test")
其他回答
如果您的shell脚本文件没有执行权限,请按照以下方法执行。
import subprocess
subprocess.run(['/bin/bash', './test.sh'])
我正在运行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子流程
子流程模块将帮助您解决这个问题。
显而易见的小例子:
>>> import subprocess
>>> subprocess.call(['sh', './test.sh']) # Thanks @Jim Dennis for suggesting the []
0
>>>
其中test.sh是一个简单的shell脚本,0是这次运行的返回值。
使用@Manoj-Govindan的答案,我发现我可以从python运行简单的shell脚本,但我拼命想要运行的脚本会因为错误而失败
Syntax error: "(" unexpected
我把第一个参数从'sh'改成了'bash',还有viola!突然,它执行了。
subprocess.call(['bash', './test.sh'])
import os
import sys
假设test.sh是您想要执行的shell脚本
os.system("sh test.sh")
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何在Makefile中设置子进程的环境变量
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 如何让“wc -l”打印没有文件名的行数?
- 有效地测试Linux上的端口是否打开?
- 排序后的语法(key=lambda:…)