【发布时间】:2021-11-07 12:51:10
【问题描述】:
我通过将export TEST1=VAL1 行添加到/home/username/.bashrc 文件中定义了一个环境变量。
在我的用户帐户的终端上使用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()
图形界面文件:
<?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>
【问题讨论】:
标签: python python-3.x linux environment-variables subprocess