如何在 python 脚本中获取 /etc/apache2/envvars?

How to source /etc/apache2/envvars within python script?

我想在 运行 apache2 -V 命令之前获取这个 /etc/apache2/envvars,它给我这个输出而不是 source

user@ubuntu16:~$ apache2 -V
[Tue Sep 14 05:01:39.045086 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_RUN_USER} is not defined
[Tue Sep 14 05:01:39.045115 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_RUN_GROUP} is not defined
[Tue Sep 14 05:01:39.045142 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Tue Sep 14 05:01:39.053712 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Tue Sep 14 05:01:39.053860 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
[Tue Sep 14 05:01:39.053878 2021] [core:warn] [pid 13942] AH00111: Config variable ${APACHE_LOG_DIR} is not defined
AH00543: apache2: bad user name ${APACHE_RUN_USER}

运行 来自终端的命令 source /etc/apache2/envvars 使上述警告消失,但我想从 python 脚本,因为我正在从我的 python 脚本调用 apache2 -V 来对输出进行一些解析。

我正在使用命令 execfile 获取文件源,但出现错误并且不确定如何解决此问题。在 python 脚本

中是否有任何正确的方法来获取此 /etc/apache2/envvars 文件
root@ubuntu16:/home/virsec# python
Python 2.7.12 (default, Mar  1 2021, 11:38:31)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile("/etc/apache2/envvars")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/etc/apache2/envvars", line 4
    unset HOME
             ^
SyntaxError: invalid syntax
>>>

execfile 用于执行 Python 代码,而不是用于 shell 变量。我猜你找到了 this answer. What it meant is not to execfile the envvars file, but to execfile some Python code, passing the required variables in the globals parameter. Cf Python 2 docs.

但是您不能从 Python source 因为它是 shell 内置的。 cf this question

你能考虑 运行 这个命令吗:

$ source envvars && python so69188563.py

# file: envvars
export ARYAMAN=1718
# file: so69188563.py
import subprocess

outcome = subprocess.run(["python", "fake_apache2.py"], stdout=subprocess.PIPE)
if outcome.returncode != 0:
    print("error !")
else:
    print(outcome.stdout)  # do something with it
# file: fake_apache2.py
import os
print(os.environ.get("ARYAMAN", "MISSING!"))  # print the value or missing

或将其放入文件中:

# !/bin/sh
# file: run.sh
source envvars
echo $ARYAMAN
python so69188563.py

并正常执行:./run.sh

无论哪种方式你都会得到 b'1718\n' 这证明 fake_apache2.py 看到了环境变量。


我的解决方案的一些细节:

  • 我假设你不想在命令行中设置它们,比如 export ARYAMAN=1718; python so69188563.py
  • 你不能做类似 source envvar && python so69188563.py 的事情,因为 shell 对每个单独的命令使用子进程,它们不共享环境变量(参见 this question 但答案很糟糕)
  • envvar中的变量必须exported,cf
  • 我不想像 this question 那样解析 (Ba)sh 语法