python - 如何从内存中运行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 脚本?
解决方案
此代码段将不起作用,因为 subprocess.Popen 期望您一次只提供一个命令。
事实并非如此。相反,它不起作用的原因是:
- 的声明
retrieve_script
必须在调用之前 - 你叫它
retrieve_script_content
而不是retrieve_script
- 你拼错
script
了scrpit
只需修复这些就可以了:
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
每次都使用系统运行脚本。
推荐阅读
- javascript - 在 Express 的上下文中,“静态”和“非静态”是什么意思?
- sql - 使用带有存在运算符的 SQL 相关子查询
- android - 使用 LiveData 观察片段内的网络变化
- xamarin.forms - Xamarin Forms 项目中的 ADB1000 部署失败(路径中有非法字符)
- debugging - 是否可以使用符号在 TRACE32 中设置范围断点?
- typescript - TypeScript 泛型,提升函数返回类型
- wordnet - 使用维基词典数据构建的图表
- docker - Docker 和非 root 用户使用 GitLab CI Runner 时如何解决权限问题?
- java - Java Pattern 单行模式
- javascript - 在水下发送 webhook(JQuery/Ajax 或无需在浏览器中打开链接)