2

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?

mokebe
  • 77
  • 1
  • 7

1 Answers1

5

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.

  • thanks, but what is the source of this problem ? I thought that double and single quotes can be used interchangeably in python? – mokebe Jul 25 '17 at 18:54
  • for strings yes ("mystring" is the same as 'mystring'), but in your case the computer parses your four single quotes and thinks that the first string ends on the second single quote, whereas you want it to end on the fourth. that is why you have to use single and double quotes – aless80 Jul 25 '17 at 18:58
  • I've updated the answer so that it makes a little more sense, but it doesn't really have anything to do with Python, it's just quoting rules. You can read up a little more on https://stackoverflow.com/questions/8254120/how-to-escape-a-single-quote-in-single-quote-string-in-bash (And also understand why this is a bad idea in the first place) – Ulises André Fierro Jul 25 '17 at 19:10