如何从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子流程
其他回答
我正在运行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是这次运行的返回值。
如果您的shell脚本文件没有执行权限,请按照以下方法执行。
import subprocess
subprocess.run(['/bin/bash', './test.sh'])
Subprocess模块是启动子进程的好模块。 你可以使用它来调用shell命令,如下所示:
subprocess.call(["ls","-l"]);
#basic syntax
#subprocess.call(args, *)
你可以在这里看到它的文档。
如果您的脚本是用.sh文件或长字符串编写的,那么您可以使用os。系统模块。调用它相当简单和容易:
import os
os.system("your command here")
# or
os.system('sh file.sh')
该命令将运行脚本一次,直到完成,然后阻塞直到退出。
有一些方法使用os.popen()(已弃用)或整个子进程模块,但这种方法
import os
os.system(command)
是最简单的方法之一。
推荐文章
- pylab和pyplot的区别是什么?
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?