首页 > 解决方案 > 如何从内存中运行python中的shell脚本?

问题描述

我正在编写的应用程序通过 HTTP 从网络检索 shell 脚本,我想在 python 中运行这个脚本但是我不想将它物理保存到硬盘驱动器,因为它的内容已经在内存中,我想只是执行它。我尝试过这样的事情:

import subprocess

script = retrieve_script()
popen = subprocess.Popen(scrpit, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdOut, stdErr = popen.communicate()

def retrieve_script_content():
    # in reality I retrieve a shell script content from network,
    # but for testing purposes I will just hardcode some test content here
    return "echo command1" + "\n" + "echo command2" + " \n" + "echo command3"

此代码段将不起作用,因为subprocess.Popen希望您一次只提供一个命令。

有没有其他方法可以从内存中运行 shell 脚本?

标签: pythonshellsubprocessshpopen

解决方案


此代码段将不起作用,因为 subprocess.Popen 期望您一次只提供一个命令。

事实并非如此。相反,它不起作用的原因是:

  1. 的声明retrieve_script必须在调用之前
  2. 你叫它retrieve_script_content而不是retrieve_script
  3. 你拼错scriptscrpit

只需修复这些就可以了:

import subprocess

def retrieve_script():
    return "echo command1" + "\n" + "echo command2" + " \n" + "echo command3"

script = retrieve_script()
popen = subprocess.Popen(script, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stdOut, stdErr = popen.communicate()
print(stdOut);

结果:

$ python foo.py
command1
command2
command3

但是,请注意,这将忽略 shebang(如果有)并sh每次都使用系统运行脚本。


推荐阅读