Python 和 Bash 命令行环境变量的处理方式不同?

标签 python bash environment-variables

$猫测试.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/

相关文章:

python - 最小化加载多对多关系的性能问题

python - Pyodbc 更新游标

python - 如何在 Keras 函数式 API 中使用逐元素乘法训练来组合 2 个向量?

python - 使用另一个 DataFrame 从 Python 中的 DataFrame 中删除记录

linux - 从文本文件中选择 md5sums 并在 Linux 中删除重复项

c++ - 为什么 getenv() 返回一个非常量字符串

bash - 只为 Mac 创建和运行 go build?

bash - 我怎样才能让 GNU 排序把大写字母放在第一位?

docker - 如何在不提交给 git 的情况下在 circleci 中传递环境变量

perl - perl 中的环境变量