2

All I know how to do is type "python foo.py" in dos; the program runs but then exits python back to dos. Is there a way to run foo.py from within python? Or to stay in python after running? I want to do this to help debug, so that I may look at variables used in foo.py (Thanks from a newbie)

3 Answers3

5

You can enter the python interpreter by just typing Python. Then if you run:

execfile('foo.py')

This will run the program and keep the interpreter open. More details here.

ChrisProsser
  • 11,110
  • 6
  • 32
  • 42
  • couldnt he also just do `from foo import *` for essentially the same behaviour? – Joran Beasley Sep 14 '13 at 20:00
  • @JoranBeasley import would just import the functions ready to be executed when required. Execfile actually executes the file, so if there are statements not inside a function these would be run. Scripts often contain an entry point such as "if __name__ == '__main__': ...". This would get run with execfile. – ChrisProsser Sep 14 '13 at 20:08
  • i didnt know that execfile would execute `if __name__ == "__main__"` – Joran Beasley Sep 16 '13 at 02:41
1

To stay in Python afterwards you could just type 'python' on the command prompt, then run your code from inside python. That way you'll be able to manipulate the objects (lists, dictionaries, etc) as you wish.

Parzival
  • 1,694
  • 3
  • 26
  • 43
1

add the module q , and use its q.d() method (I did it with easy_install q) https://pypi.python.org/pypi/q

import q
....
#a bunch of code in foo.py
...
q.d()

that will give you a console at any point in your program where you put it that you can interact with your script

consider the following foo.py

import q
for x in range(5):
    q.d()

now examine what happens when I run it

C:\Python_Examples>python qtest.py
Python console opened by q.d() in <module>
>>> print x
0
>>>
Python console opened by q.d() in <module>
>>> print x
1
>>>
Python console opened by q.d() in <module>
>>> print x
2
>>>
Python console opened by q.d() in <module>
>>> print x
3

(note to continue execution of script use ctrl+z)

in my experience this has been very helpful since you often want to pause and examine stuff mid execution (not at the end)

Joran Beasley
  • 93,863
  • 11
  • 131
  • 160