如何访问'missing'环境变量?



我在bashrc中添加了一个环境变量,但是我无法在Python文件中使用os. environment .get看到这些变量。

我在Raspberry Pi 4上使用Raspbian。

我在"bashrc"中设置了一个环境变量,如下所示:

export DB_USER='emailAddress@gmail.com'

在终端上调用以下命令时:

$ env

…我在一个24项的列表中找到DB_USER。

但是,当我在Python文件(该文件由bash脚本调用)中使用以下命令时:

import os
...
try:
    with open("tempFile.txt", "a") as f:
        f.write(str(os.environ))
        f.close()
except FileNotFoundError:
    print("FileNotFoundError")
except IOError:
    print("IOError")

则' DB_USER '不在"tempFile.txt"的11个条目列表中。

我如何访问24项的列表,以便我可以使用' DB_USER '条目?

感谢

因为这是一个服务(所以,不是你的用户,根据Chepner的评论)调用这个东西,看起来你想让环境变量在系统范围内可用。

/etc/environment可以满足您的需求。你只需要加上

DB_USER=emailAddress@gmail.com

。(不,不要使用export)

请参阅https://superuser.com/questions/664169/what-is-the-difference-between-etc-environment-and-etc-profile和https://raspberrypi.stackexchange.com/questions/37771/setting-system-wide-path-not-working-in-etc-environment(其中讨论使用/etc/profile.d代替,但类似的概念-这可能是我采取的方法,在测试了基本的基于/etc/environment的修复后)

试试这样:

import os, subprocess
# try to simulate being the user so you can import/capture the env as that user
cmd = 'env -i sh -c ". /home/user/.bashrc && env"'
try:
    with open("tempFile.txt", "a") as f:
        for line in subprocess.getoutput(cmd).split("n"):
        f.write(str(line))
        f.close()
except FileNotFoundError:
    print("FileNotFoundError")
except IOError:
    print("IOError")

我已经设法找到了一个解决方案,感谢这篇文章中给出的建议。

我目前在脚本中使用/etc/environment,如下所示:

  # get environmental variables
  source /etc/environment
  
  afile='<file path and name>‘
  date >> $afile
  
  echo >> $afile
  echo Straight from set >> $afile
  echo $DB_USER_environment >> $afile
  echo >> $afile
  
  echo Via a variable in the script >> $afile
  db_user02=$DB_USER_environment
  echo $db_user02 >> $afile
  
  echo >> $afile

这将以下内容添加到afile

Sat 12 Nov 11:56:11 GMT 2022
Straight from set
emailAddress@gmail.com
Via a variable in the script
emailAddress@gmail.com

我想看看etc/配置文件。d (@JL Peyret), Python (@TheAnalogyGuy)和systemd (@MattDMo)建议。

感谢所有的回复

最新更新