floyd floyd - 2 months ago 8x
Python Question

syntax error in the file name when I run a python script twice?

When I try to use the

command twice in IPython, I get a syntax error the second time:

In [2]: run control.py

In [3]: run control.py
File "<ipython-input-3-3e54b0f85f39>", line 1
run control.py
SyntaxError: invalid syntax

In my script I implemented a class and made an object from that class.

I tried to make a new python script without any classes and objects, and it works fine when I run it many times, why do classes and objects produce the problem?

I use ipython on Windows (NOT the notebook).


The correct ipython command is %run, with the % prefix. Without the prefix can work, but only if you don't also have a Python global name run masking the command.

Because %run script.py runs the script inside the IPython interpreter, any globals that script sets are available in the interpreter after the script has completed. And your console.py script set the global name run, and that name is now masking the %run command.

In other words, this has nothing to do with classes or instances. Either use %run to run the script, or don't use the name run anywhere in the script itself.

Demo using a little script setting run; note how %run continues to work, and how deleting the name run can also make run demo.py work again:

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"