推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
18870715400
V2EX  ›  Python

关于 Python 中 os 模块怎么获取环境变量的问题

  •  
  •   18870715400 · Apr 20, 2021 · 2149 views
    This topic created in 1875 days ago, the information mentioned may be changed or developed.
    import os
    os.getenv("hello")
    

    如上所示, 如果我在终端中使用 sudo python3 执行上面代码, 获取到的就是系统的环境变量. 我的有一个脚本是使用 root 权限启动的, 导致我获取到的环境变量是系统级别的环境变量, 那么我这边有没有什么 python 方法在 root 用户运行脚本的时候获取到这个"hello"的用户级别的环境变量呢, 各位大佬有方法么?

    10 replies    2021-05-08 16:38:51 +08:00
    learningman
        1
    learningman  
       Apr 20, 2021
    subprocess.popen
    su user && export
    行不(
    ClericPy
        2
    ClericPy  
       Apr 20, 2021
    既然是 linux..

    1. sudo su -u hello python3 xx.py
    2. export a=b; python3 yy.py
    3. source xxx; python3 zz.py

    随手打的, 不确定具体可用
    18870715400
        3
    18870715400  
    OP
       Apr 20, 2021
    @learningman 你的这个方法好像不行, 我在终端执行直接进入 bash 命令行了.
    18870715400
        4
    18870715400  
    OP
       Apr 20, 2021
    @ClericPy 这边用的是 mac 系统
    Jirajine
        5
    Jirajine  
       Apr 20, 2021 via Android   ❤️ 1
    环境变量没有什么系统的、用户的之分,都是从父进程继承的。你用 root 启动获取到的就是 root 用户的环境变量。
    你可以让 sudo 为你保留环境变量,或以普通用户启动以后再提权。
    ungrown
        6
    ungrown  
       Apr 21, 2021
    变量如果隐私不敏感的话,可以先用非 root 用户权限跑个脚本把变量保存到配置文件
    18870715400
        7
    18870715400  
    OP
       Apr 21, 2021
    这边发现变量的值使用的是用用户名字直接拼接的, 这边就不用获取变量了.
    no1xsyzy
        8
    no1xsyzy  
       Apr 21, 2021
    这显然是一个 X-Y 问题
    sudo 会影响非常多的环境变量,试试 sudo env | diff <(env) /dev/fd/0

    另外,用户名拼接实际上很可能也是误解。比如 $HOME 其实是从 /etc/passwd 读取的,只不过默认采用 /home/$USER 罢了。
    arischow
        9
    arischow  
       Apr 21, 2021
    在该项目中的 virtualenv 管理对应的环境变量
    julyclyde
        10
    julyclyde  
       May 8, 2021
    说白了这事和 python 没啥关系
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1388 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 17:08 · PVG 01:08 · LAX 10:08 · JFK 13:08
    ♥ Do have faith in what you're doing.