带有“-c”和缩进问题的Python解释器调用

时间:2010-12-29 14:39:44

标签: python cmd syntax-error interpreter

我正在尝试使用“-c”参数调用Python,以便我可以轻松地运行一些任意的python代码,如下所示: python.exe -c "for idx in range(10): print idx" 现在这个代码在我的批处理文件中工作正常,但是,当我想做更多的事情时,我遇到了问题。

考虑以下Python代码:

foo = 'bar'
for idx in range(10):
    print idx

然后这将在stdout上给你0-9。但是,如果我将其折叠成一行,使用分号作为分隔符,则获得以下内容:

foo = 'bar';for idx in range(10):    print idx

并尝试使用python.exe -c运行它,它会引发一个语法错误:

C:\Python>python.exe -c "foo = 'bar';for idx in range(10):    print idx"
  File "<string>", line 1
    foo = 'bar';for idx in range(10):    print idx
                  ^
SyntaxError: invalid syntax

任何人都知道如何在不切换到单独的.py文件的情况下实际使用它吗?

我是在.cmd批处理文件中运行它,通过如下调用方法:

call python.exe -c "blah blah"

生成相同的错误。

2 个答案:

答案 0 :(得分:3)

您需要输入命令字符串作为多行参数。使用linux,这就像使用enter键一样简单,例如(请注意,bash添加了>个字符,我没有必要输入它们:

$ python -c "foo = 'bar'
> for idx in range(10):
>     print idx"

在Windows上,您需要在按Enter键之前键入^键,并留下一个空行以获取换行符,例如(More?

添加了cmd
C:\> python.exe -c "foo = 'bar'^
More? 
More? for idx in range(10):^
More? 
More?     print idx"

答案 1 :(得分:2)

使用换行符分隔语句。这就是我进入shell的方式:

$ python -c "foo = 'bar'
for idx in range(10): print idx"

你写的内容不起作用,因为分号比冒号更紧密,所以它会混淆。相比之下,这有用,例如:

$ python -c "foo = 'bar'; print foo"