-1

I noticed that all the modules I import are removed (I can't use them anymore without importing them again) after I run a python file in the python IDE. Here is the view of my IDE:

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import os
>>> os
<module 'os' from 'C:\\Users\\MN\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>
>>> 
 RESTART: C:/Users/MN/AppData/Local/Programs/Python/Python37/python file just ran.py 
A python file just ran
>>> os
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    os
NameError: name 'os' is not defined
>>> 

For deep view, this was in my file:

print("A python file just ran")

Why is this happening and how to make the imported modules stay in there without importing them again?

Nouman
  • 6,947
  • 7
  • 32
  • 60

2 Answers2

1

I'm not sure if you can make them stay, sorry.

Python restarts when you launch a file in IDLE (it even states RESTART).

Edit: Try defining variables, methods or classes - they too will be gone, not just your imports.

Edit two: You can import your file (python will automaticly execute it), that will not restart python so you will keep what you defined/imported.

iko
  • 46
  • 5
0

Maybe just to add why this is the case...

Every Python program must have some module that is in "control" of the program. This is the same as in C where you have a "main".

If you want to use functions from file_just_ran.py, then you should define those as functions and then import them into your session. Then the session is in control.

If you want the scrip to be in control, then you must do these import etc either in the script, or in a file that that script can import.

Otherwise, how does the interpreter know what to do? You're trying to execute commands in a running python program?

If you just want to run scripts and code in an interpreter in parallel, then open two sessions.

Neil
  • 3,020
  • 4
  • 25
  • 48