Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running python script in interactive python prompt and keep the variables? [duplicate]

Tags:

python

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.

like image 821
athos Avatar asked Jun 26 '17 11:06

athos


People also ask

How do I run a Python script in interactive mode?

A widely used way to run Python code is through an interactive session. To start a Python interactive session, just open a command-line or terminal and then type in python , or python3 depending on your Python installation, and then hit Enter .

What is difference between interactive mode and script mode in Python?

Output: Script mode produces output that can be saved and reused. Interactive mode produces output that is displayed on the screen and then disappears. Save: Script mode can be saved in a text file. Interactive mode cannot be saved, but the user can type commands in an editor and save it as a script file.

Can you run the same Python script twice?

You can run multiple instances of a python script from a shell however from within a python program without the use of multithreading/multiprocessing the GIL limitation will impact what you are trying to do.

How do I create an interactive code in Python?

On Windows, bring up the command prompt and type "py", or start an interactive Python session by selecting "Python (command line)", "IDLE", or similar program from the task bar / app menu. IDLE is a GUI which includes both an interactive mode and options to edit and run files.


2 Answers

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.

like image 196
Sawant Avatar answered Oct 16 '22 05:10

Sawant


Use

C:\python>python -i first.py

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

like image 41
Christian König Avatar answered Oct 16 '22 07:10

Christian König