How to run script from interpreter?

Chris Angelico rosuav at gmail.com
Fri Feb 16 17:34:34 EST 2018


On Sat, Feb 17, 2018 at 9:18 AM, windhorn <aewindhorn at gmail.com> wrote:
> Yes, it's been covered, but not quite to my satisfaction.
>
> Here's an example simple script:
>
> # Very simple script
> bar = 123
>
> I save this as "foo.py" somewhere Python can find it
>
>>>> import foo
>>>> bar
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'bar' is not defined
>
> # Oops, it's in a different namespace and I have to prefix EVERYTHING with "foo.". This is inconvenient.
>
>>>> foo.bar
> 123
>
> Start a new session...
>
>>>> from foo import *
>>>> bar
> 123
>
> Do a little editing:
>
> # Very simple (new) script
> bar = 456
>
> Save as foo.py, back to the interpreter:
>
>>>> reload(foo)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> NameError: name 'foo' is not defined
>
> # Oops, it's not in the namespace, so there is NO way to use reload
>
> Start a new session...
>
>>>> execfile('foo.py')
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> IOError: [Errno 2] No such file or directory: 'foo.py'
>
> # Oops, it's on the path, but execfile can't find it
>
>>>> import os,sys
>>>> os.chdir('W:/Code')
>>>> execfile('foo.py')
>>>> bar
> 456
>
> Do some more editing:
>
> # Very simple (even newer) script
> bar = 789
>
> Save it as foo.py, back to the interpreter:
>
>>>> execfile('foo.py')
>>>> bar
> 789
>
> That works, but nothing is very convenient for debugging simple scripts. If I run the script from a command prompt it works, but I lose all my other stuff (debugging functions, variables, etc.).
>
> More a comment than a question but seems like sometimes execfile() is the right tool.

Or possibly you want to exit completely, and run "python3 -i foo.py",
which will drop you into the interactive interpreter after running the
script. That's safer than trying to re-execute an already-loaded
module.

ChrisA



More information about the Python-list mailing list