如何通过python源代码脚本

2024-09-30 12:31:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以像在终端中使用bash命令一样简单地获取bash脚本(不使用shebang),但也尝试通过python命令来实现同样的操作

sourcevars = "cd /etc/openvpn/easy-rsa && . ./vars"
runSourcevars = subprocess.Popen(sourcevars, shell = True)

或者

^{pr2}$

我收到:

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)

Tags: buildbashtrueeasyetccdvarsshell
1条回答
网友
1楼 · 发布于 2024-09-30 12:31:23

这本身并没有什么问题:

# 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,它们的状态不会继续。在

因此,合并成一个单独的调用:

^{pr2}$

…这样您就可以在与实际源代码脚本的shell调用相同的shell调用中使用脚本源代码的结果。在


或者(这就是我要做的),要求您的Python脚本由一个shell调用,这个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)

相关问题 更多 >

    热门问题