使用 Python 获取用户的环境变量

Getting Environment Variables Of An User By Using Python

我通过在 /home/username/.bashrc 文件中添加 export TEST1=VAL1 行来定义环境变量。

当我的用户帐户在终端上使用 printenv 命令时,会列出此变量。但是当使用下面的python代码时不列出:

variables = subprocess.check_output("printenv", shell=True, executable='/bin/bash').decode()

使用Python.

列出这个变量的解决方案是什么
OS: Debian-like Linux, Python: 3.9

python 中 运行 终端命令的示例代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

builder = Gtk.Builder()
builder.add_from_file('test.ui')
window1 = builder.get_object('window1')

class Signals:
    def on_window1_destroy(self, widget):
        Gtk.main_quit()

builder.connect_signals(Signals())

import subprocess
variables = subprocess.check_output("/bin/bash -l -c printenv", shell=True).decode()
f = open("/tmp/env.txt","w")
f.write("%s" % (variables))
f.close()

window1.show_all()
Gtk.main()

GUI 文件:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.22.1 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <property name="default_width">300</property>
    <property name="default_height">300</property>
    <child>
      <placeholder/>
    </child>
    <child>
      <object class="GtkTreeView" id="treeview1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <child internal-child="selection">
          <object class="GtkTreeSelection"/>
        </child>
      </object>
    </child>
  </object>
</interface>

使用 shell,登录和非登录执行之间存在差异(参见 man bash)。

executable属性不接受参数,只是一个可执行文件。

所以尝试:

#! /usr/bin/python
import subprocess
variables = subprocess.check_output("/bin/bash -c printenv", shell=True).decode()
f = open("/tmp/env.txt","w")
f.write("%s" % (variables))
f.close()

输出不包含 TEST1 变量。

使用 bash -l 选项:

#! /usr/bin/python
import subprocess
variables = subprocess.check_output("/bin/bash -l -c printenv", shell=True).decode()
f = open("/tmp/env.txt","w")
f.write("%s" % (variables))
f.close()

输出包含 TEST1 个变量。