$猫测试.py
#!/usr/bin/env python
# coding=utf-8
import os
print (os.environ.get('test'))
$ test=4 python 测试.py
4
$测试=4; python 测试.py
None
在 shell 中我与 python 有所不同:
$测试=4; echo $测试
4
但是:
$测试=2
$ test=4 echo $test
2
所以我对 python 和 bash 如何处理这种情况感到困惑。谁能解释一下?
最佳答案
这就是shell和环境变量的区别。
这里,
test=4 python test.py
将 test=4
传递给 python
的环境,因此您将在脚本中获取变量 test
。
鉴于
test=4; python test.py
创建一个仅在当前 shell session 中可用的 shell 变量(这就是您从 shell 中获取值的原因),即不会传播到环境中。
要创建一个变量环境变量,以便所有子进程都继承该变量,即使该变量在进程环境中可用,任何 POSIX shell 上的常用方法是导出
变量:
export test=4; python test.py
在你的最后一个案例中:
$ test=2
$ test=4 echo $test
2
变量 test
的扩展发生在 echo
内置函数运行之前。
您需要使用某种方法来保留展开以供以后使用:
$ test=2
$ test=4 sh -c 'echo $test'
4
关于Python 和 Bash 命令行环境变量的处理方式不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43509728/