How to run script from interpreter?

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 16 17:47:23 EST 2018


On Fri, Feb 16, 2018 at 3:18 PM, 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


You didn't need to start a new session here. "from foo import *" works
just as well in the existing session.


> 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


Sure there is.

py> import foo  # Get the module to reload
py> reload(foo)  # Reload it
py> from foo import *  # Update all the names previously *-imported


> 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


execfile doesn't use the path; that's not what it's meant for.



More information about the Python-list mailing list