Why is it wrong to write "for" after "import os;"

I am using Windows 7 with official Python 2.7.

On the cmd command line, I can write

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

However, this is not true:

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

Can someone please help me? I really hope to write the importfollowing statements on the same line, because I would like to write a doskey command like this to make an easily readable PATH list:

doskey lpath=python -c "import os; for p in os.environ['PATH'].split(';'): print p"
+4
source share
2 answers

How about using __import__instead?

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

UPDATE

Alternative: replace ;with a new line.

python -c "import os; print os.environ['PATH'].replace(';', '\n')"
+4
source

This is similar to a language syntax feature. Note:

, :

stmt: simple_stmt | compound_stmt

:

simple_stmt: small_stmt (';' small_stmt)* [';'] NEWLINE
small_stmt: (expr_stmt | del_stmt | pass_stmt | flow_stmt |
             import_stmt | global_stmt | nonlocal_stmt | assert_stmt)

, import_stmt ( ). , ; .

, :

compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated

for ( ) .

: https://docs.python.org/3/reference/grammar.html?highlight=grammar

+4

Source: https://habr.com/ru/post/1543425/


All Articles