怎么写"对于"在" import os;"

时间:2014-06-05 14:41:36

标签: python

我正在使用Windows 7和官方Python 2.7。

在CMD命令行上,我可以写

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

然而,这是错误的:

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

有人可以帮帮我吗?我真的希望在一行中编写import和后续语句,因为我想写一个这样的doskey命令,以便制作一个易于阅读的PATH列表:

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

2 个答案:

答案 0 :(得分:4)

如何使用__import__呢?

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

<强>更新

替代方案:用换行符替换;

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

答案 1 :(得分:4)

这似乎是语言语法的一个特点。观察:

语句可以是简单语句或复合语句:

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