Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come it is wrong to write "for" after "import os;"

Tags:

python

I'm using Windows 7 with official Python 2.7 .

On CMD command line, I can write

python -c "import os; print os.environ['PATH'].split(';');"

However, this is wrong:

C:\>python -c "import os; for p in os.environ['PATH'].split(';'): print p"
  File "<string>", line 1
    import os; for p in os.environ['PATH'].split(';'): print p
                 ^
SyntaxError: invalid syntax

Could someone please help me out? I really hope to write import and subsequent statements in one line, because I'd like to write a doskey command like this, to make a easy-to-read PATH listing:

doskey lpath=python -c "import os; for p in os.environ['PATH'].split(';'): print p"
like image 220
Jimm Chen Avatar asked Feb 13 '23 19:02

Jimm Chen


1 Answers

How about using __import__ instead?

python -c "for p in __import__('os').environ['PATH'].split(';'): print p"

UPDATE

Alternative: replacing ; with newline.

python -c "import os; print os.environ['PATH'].replace(';', '\n')"
like image 156
falsetru Avatar answered Feb 15 '23 10:02

falsetru