gpt4 book ai didi

python - 如何通过 python 源脚本

转载 作者:太空宇宙 更新时间:2023-11-04 10:16:56 24 4
gpt4 key购买 nike

我可以像终端中的 bash 命令一样轻松获取 bash 脚本(没有 shebang),但尝试通过 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)

我收到:

Please source the vars script first (i.e. "source ./vars") Make sure you have edited it to reflect your configuration.

怎么回事,如何正确执行?我在这里阅读了一些主题,例如 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)

最佳答案

这本身绝对没有错:

# 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 的状态;每次您使用 shell=True 创建一个新的 Popen 对象时,它都会启动一个新的 shell——它们的状态不会被保留。

因此,合并成一个调用:

prefix = "cd /etc/openvpn/easy-rsa && . ./vars && "
cmd = "/etc/openvpn/easy-rsa/clean-all"
runCmd = subprocess.Popen(prefix + cmd, shell=True)

...这样您就可以在与实际获取脚本的 shell 调用相同的 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)

关于python - 如何通过 python 源脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34776070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com