我两次运行python脚本时文件名中的语法错误?

flo*_*oyd 1 python windows ipython python-2.7

当我尝试run在IPython中两次使用命令时,第二次出现语法错误:

In [2]: run control.py

In [3]: run control.py
  File "<ipython-input-3-3e54b0f85f39>", line 1
    run control.py
              ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

在我的脚本中,我实现了一个类并从该类中创建了一个对象。

我试图制作一个没有任何类和对象的新python脚本,当我多次运行它时,它运行良好,为什么类和对象会产生问题?

我在Windows上使用ipython(不是笔记本电脑)。

Mar*_*ers 5

正确的ipython命令为%run,带有%前缀。没有前缀可以使用,但前提是您还没有run掩盖命令的Python全局名称。

因为在IPython解释器中%run script.py运行脚本,所以脚本完成后,在解释器中可以使用脚本集的所有全局变量。您的脚本设置了全局名称,该名称现在掩盖了该命令。console.pyrun%run

换句话说,这与类或实例无关。要么用于%run运行脚本,要么不在run脚本本身的任何位置使用名称。

演示使用一点脚本设置run; 请注意如何%run继续工作,以及删除名称run也可以使run demo.py工作再次生效:

In [1]: %cat demo.py
print('Setting the name "run" to "foo"')
run = 'foo'

In [2]: run demo.py
Setting the name "run" to "foo"

In [3]: run  # the global name is set
Out[3]: 'foo'

In [4]: run demo.py
  File "<ipython-input-4-3c6930c3028c>", line 1
    run demo.py
           ^
SyntaxError: invalid syntax


In [5]: %run demo.py
Setting the name "run" to "foo"

In [6]: del run  # deleting the global name makes 'run script' work again

In [7]: run demo.py
Setting the name "run" to "foo"
Run Code Online (Sandbox Code Playgroud)