在python函数中运行shell脚本并从脚本中获取数据
我将要编写一个python脚本,它将调用一个或多个shell脚本。我无法仅使用python执行某些命令,因此我不得不在python函数中运行shell脚本 现在,我想知道是否可以从shell脚本中获取任何数据:我假设我可以使用subprocess.Popen从脚本中获取退出代码,但这就是我可以从shell脚本中获取的全部信息吗 理想情况下,我不需要太多东西,但我希望将shell脚本设置为在进程通过或失败时返回X或Y,如果出现问题,则返回Z,但这取决于具体原因,并将其传递给python函数,该函数将相应地执行 这是可能的,还是我在浪费时间试图整合两者在python函数中运行shell脚本并从脚本中获取数据,python,bash,Python,Bash,我将要编写一个python脚本,它将调用一个或多个shell脚本。我无法仅使用python执行某些命令,因此我不得不在python函数中运行shell脚本 现在,我想知道是否可以从shell脚本中获取任何数据:我假设我可以使用subprocess.Popen从脚本中获取退出代码,但这就是我可以从shell脚本中获取的全部信息吗 理想情况下,我不需要太多东西,但我希望将shell脚本设置为在进程通过或失败时返回X或Y,如果出现问题,则返回Z,但这取决于具体原因,并将其传递给python函数,该函数
import sys
from subprocess import Popen, PIPE; STDOUT
pyversion = sys.version_info.major
class interact():
def __init__(self, c):
self.handle = Popen(c, stdin=PIPE, stdout=PIPE, stderr=STDOUT, shell=True)
sleep(1)
def send(self, what):
for c in what:
sys.stdout.write(c)
if pyversion == 3:
self.handle.stdin.write(bytes(c, 'UTF-8'))
else:
self.handle.stdin.write(c)
sys.stdout.flush()
sys.handle.stdin.flush()
sleep(0.05)
def getrow(self):
return self.handle.stdout.readline()
def poll(self):
return self.handle.poll()
def done(self):
if self.poll() == 1:
return 'Return Y'
return 'Return X'
def close(self):
self.handle.stdout.close()
self.handle.stdin.close()
您可以这样做,您有自己的结构,根据退出代码或当前运行代码返回您想要的任何内容,如果流程尚未完成,则返回的代码为None
只需将其用作:
handle = interact('ls -lah')
while handle.poll() is None:
pass
result = handle.done()
或者tweek it,我在执行SSH调用时使用了这段代码作为基本结构,并生成了OpenSSL密钥,工作起来很有魅力,但我认为我必须tweek it才能使用SSH(找不到代码atm)
您可以添加以下内容:
try:
self.handle.stdin.write(...)
except:
self.error = True
在done()
中,如果发生错误,只需返回Z
(如您所述)
注意:如果不调用大量输出脚本/命令的getrow()
,缓冲区将溢出并挂起整个内容,因此请确保偶尔点击该按钮,或使用子进程删除stdout=PIPE,stderr=stdout
:
import subprocess
p = subprocess.Popen(['ls', '-ltr'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
ret = p.wait()
out, err = p.communicate()
print out
我不会使用shell
参数,因为它只会使你的生活复杂化。如果要异步执行操作,可以使用poll()
而不是wait()
有关详细信息,请阅读子流程文档:
这确实是可能的。完整阅读
子流程
上的文档。您可能特别想查看一下check_output
。这样您就无法控制stdout
tho,正如前面提到的,您可能会溢出缓冲区,最终导致应用程序挂起:)shell
不会让您的生活复杂化,如果它能让您的生活更轻松的话?