Python和环境变量

标签 python bash python-2.7 unix

在 ubuntu 终端中执行以下命令我得到了预期的结果:

$export number=3
echo $number ###3
$python
>>>import os
>>>print(os.environ['number']) ###prints 3

同时:

$python -c 'import os;print(os.environ['number'])'

结果:NameError:名称“number”未定义。

为什么?是否可以使用 python -c 获取环境变量?

最佳答案

确保将单引号更改为双引号(至少是外部引号)以避免出现该问题

python -c "导入 os;print(os.environ['number'])" 3

工作得很好,因为我的单引号在双引号内。

编辑:您的示例的问题不在于您在 Python 中使用单引号,问题在于您的 shell 正在解释这些单引号。

来自 bash 手册页:

A single quote may not occur between single quotes, even when preceded by a backslash.

关于Python和环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311301/

相关文章:

python - 这种情况下如何让多个python程序进行通信呢?

python - Python 中的位运算

python - Jupyter 笔记本 Ipython : Groupby based on the values alphabetically

Bash:重定向文件描述符

python - “模块”对象没有属性 'SummaryWriter'

python - 在python中将网格变成棋盘图案?

python - 带尖音符的拉丁字母 : DjangoUnicodeDecodeError

python - 是否可以将范围作为变量 "var = k:k+number"

git - 如何使用单个脚本克隆所有 git bitbucket 存储库

linux - 初始化脚本 '/dev/tty: No such device or address' 重定向错误