我可以在终端中将bash脚本(没有shebang)轻松地作为bash命令来源但是尝试通过python命令执行相同的操作
sourcevars = "cd /etc/openvpn/easy-rsa && . ./vars"
runSourcevars = subprocess.Popen(sourcevars, shell = True)
或
sourcevars = [". /etc/openvpn/easy-rsa/vars"]
runSourcevars = subprocess.Popen(sourcevars, shell = True)
我收到:
请首先获取vars脚本(即“source ./vars”) 确保您已对其进行了编辑以反映您的配置。
问题是什么,如何正确地做到这一点?我在这里阅读了一些主题,例如here,但无法使用给定的建议解决我的问题。请用例子说明。
更新:
# os.chdir = ('/etc/openvpn/easy-rsa')
initvars = "cd /etc/openvpn/easy-rsa && . ./vars && ./easy-rsa ..."
# initvars = "cd /etc/openvpn/easy-rsa && . ./vars"
# initvars = [". /etc/openvpn/easy-rsa/vars"]
cleanall = ["/etc/openvpn/easy-rsa/clean-all"]
# buildca = ["printf '\n\n\n\n\n\n\n\n\n' | /etc/openvpn/easy-rsa/build-ca"]
# buildkey = ["printf '\n\n\n\n\n\n\n\n\n\nyes\n ' | /etc/openvpn/easy-rsa/build-key AAAAAA"]
# buildca = "cd /etc/openvpn/easy-rsa && printf '\n\n\n\n\n\n\n\n\n' | ./build-ca"
runInitvars = subprocess.Popen(cmd, shell = True)
# runInitvars = subprocess.Popen(initvars,stdout=subprocess.PIPE, shell = True, executable="/bin/bash")
runCleanall = subprocess.Popen(cleanall , shell=True)
# runBuildca = subprocess.Popen(buildca , shell=True)
# runBuildca.communicate()
# runBuildKey = subprocess.Popen(buildkey, shell=True )
更新2
buildca = ["printf '\n\n\n\n\n\n\n\n\n' | /etc/openvpn/easy-rsa/build-ca"]
runcommands = subprocess.Popen(initvars+cleanall+buildca, shell = True)
答案 0 :(得分:4)
这本身并没有任何问题:
# What you're already doing -- this is actually fine!
sourcevars = "cd /etc/openvpn/easy-rsa && . ./vars"
runSourcevars = subprocess.Popen(sourcevars, shell=True)
# ...*however*, it won't have any effect at all on this:
runOther = subprocess.Popen('./easy-rsa build-key yadda yadda', shell=True)
但是,如果后来尝试运行第二个subprocess.Popen(..., shell=True)
命令,您将看到它没有通过获取该配置设置的任何变量。
这是完全正常的预期行为:使用source
的整个过程就是修改活动shell的状态;每次使用Popen
创建一个新的shell=True
对象时,它都会启动一个新shell - 它们的状态不会被转移。
因此,合并为一个电话:
prefix = "cd /etc/openvpn/easy-rsa && . ./vars && "
cmd = "/etc/openvpn/easy-rsa/clean-all"
runCmd = subprocess.Popen(prefix + cmd, shell=True)
...这样您就可以在与实际源脚本相同的shell调用中使用脚本来获取结果。
或者(这就是我要做的),要求你的Python脚本由一个已经在其环境中拥有必要变量的shell调用。因此:
# ask your users to do this
set -a; . ./vars; ./yourPythonScript
...如果人们不这么做,你就会出错:
import os, sys
if not 'EASY_RSA' in os.environ:
print >>sys.stderr, "ERROR: Source vars before running this script"
sys.exit(1)