我的 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/