9

I understand from How do I run a Python program? that in command prompt i can use

C:\python>python first.py

, to run first.py.

But, is it possible, that after i entered the interactive python prompt, by runnning

C:\python>python 

and see the >>> python indication, run first.py, and after finished running first.py, back to the interactive python prompt, I could see variables defined inside first.py?

For example, if first.py created some variables inside, e.g. by

(x,y) = [3,5]

, is it possible that after running first.py and back to the interactive python prompt, x and y are still there?

Running windows shell commands with python shows how to run the windows shell command in python, so in the interactive python prompt, i could actually use

>>>os.system('python first.py')

to run first.py, but x and y defined inside are lost after running.

athos
  • 6,120
  • 5
  • 51
  • 95

2 Answers2

18

Try the following for Python 2.x:

>>> execfile('first.py')

For Python 3.x, try this:

>>> exec(open("./first.py").read())

The variables should then be available to you.

Sawant
  • 4,321
  • 1
  • 27
  • 30
14

Use

C:\python>python -i first.py

to run the script and get the interactive shell in the same namespace afterwards.

Christian König
  • 3,437
  • 16
  • 28
  • This way the script is executed the same way OP does it right now, with added interactive shell. `import` would indeed not work with a `if __name__ == "__main__":`-statement. – Christian König Jun 26 '17 at 11:28