How to run script from interpreter?
windhorn
aewindhorn at gmail.com
Fri Feb 16 17:18:16 EST 2018
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.
Regards,
Allen
More information about the Python-list
mailing list