mokebe mokebe - 3 years ago 95
Python Question

Python and environmental variables

Executing following commands in ubuntu terminal I have expected results:

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


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


Results in : NameError : name 'number' is not defined.

Why? Is it possible to get env variables with python -c?

Answer Source

Make sure you change your single quotes for double quotes (the outer ones, at least) to avoid having that problem

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

Works just fine because my single quotation marks are inside double quotes.

Edit: The problem with your example is not the fact that you're using single quotes within Python, the problem is that it's your shell that's interpreting those single quotes.

From the bash man page:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download