python - 如何在传递输入参数后从Python执行shell脚本

标签 python linux bash shell ubuntu

我的 JSON 文档 jsonStr 中有一个 shell 脚本,我可以使用 Python 子进程模块执行它,并且工作正常。

下面是我的 Python 脚本,如果我执行 shell 脚本而不传递任何内容,它可以正常工作 -

import subprocess
import json

testing = "HelloWorld"

jsonStr = '{"script":"#!/bin/bash \\n STRING=\'Hello World\' \\n echo $STRING \\n"}'

j = json.loads(jsonStr)

print "start"
subprocess.call(j['script'], shell=True)
print "end"

现在有什么方法可以将变量值从 Python 脚本传递到 json 文档中的 shell 脚本吗?这意味着我需要将 testing 值传递给我的 shell 脚本,然后在从子进程模块执行后从 shell 脚本打印出 testing 的值。

这可以做到吗?

最佳答案

你不能用这个吗?

import subprocess
import json

testing = "HelloWorld"

jsonStr = '{"script":"#!/bin/bash \\n STRING=\'%VP%\' \\n echo $STRING \\n"}'.replace('%VP%', testing)

j = json.loads(jsonStr)

print "start"
subprocess.call(j['script'], shell=True)
print "end"

在 JSON 中,您可以有占位符,并且可以替换该占位符,而不是动态地将变量传递给变量。

关于python - 如何在传递输入参数后从Python执行shell脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20758005/

相关文章:

python - 如何在pygame中用鼠标滚动图像?

python - 具有取决于输入参数的通用理解返回类型的函数?

linux - 如何将文件夹中的文件列表发送到Linux中的txt文件

linux - 脚本在 raspbian 中运行两次

linux - 如何删除文件名中的转义字符?

python - 通过 virtualenv 将自制的 python 模块部署到工作环境中是一个好主意吗?

python - 三个应用程序同一个命名空间

linux - Bash 命令只移动一些文件?

linux - 从 *.txt 搜索并将文件复制到新目录

java - 来自 Java 的 clang 的 `pkg-config` 参数