How to import a python file in python script more than once

Is it possible to import a python file more than once in a python script because i run a loop back to my driver file in a function by using the import command but it only works once? thanks

edit: Resolved myself thanks


Asked by: John925 | Posted: 27-01-2022






Answer 1

You most probably should not use import for what you are trying to do.

Without further information I can only guess, but you should move the code in the module you import from the top level into a function, do the import once and than simply call the function from you loop.

Answered by: Lily353 | Posted: 28-02-2022



Answer 2

The easiest answer is to put the code you are trying to run inside a function like this

(inside your module that you are importing now):

def main():
    # All the code that currently does work goes in here 
    # rather than just in the module

(The module that does the importing)

import your_module #used to do the work

your_module.main() # now does the work (and you can call it multiple times)
# some other code
your_module.main() # do the work again

Answered by: Kirsten583 | Posted: 28-02-2022



Answer 3

The import statement -- by definition -- only imports once.

You can, if you want, try to use execfile() (or eval()) to execute a separate file more than once.

Answered by: Melissa376 | Posted: 28-02-2022



Answer 4

While Tom Ley's answer is the correct approach, it is possible to import a module more than once, using the reload built-in.

module.py:
print "imported!"

>>> import module
imported!
>>> reload(module)
imported!
<module 'module' from 'module.pyc'>

Note that reload returns the module, allowing you to rebind it if necessary.

Answered by: Chelsea766 | Posted: 28-02-2022



Similar questions

import error in python even after having init file and python path

I am trying to import a file in python my directory structure is maindir __init__.py constants.py subdirectory __init__.py code.py I am trying to import constants in the code file import sys sys.path.append('/home/ching/maindir') from maindir import constants even after that I am getting this error


Import error in Python 3 but works with Python 2

I want to work with Python v3.5.2, but my laptop also has Python 2.7.10 installed (it's a MacBook). I have a simple Python project structure like the following. Note, there might be artifacts that are showing because I am using IntelliJ as the IDE (e.g. *.pyc files and *.iml file). . ├── io │   ├── __init__.py │   ├── __init__.pyc │   ├── __pycache__ │   │   └── __init__.cpython-35.pyc │   └── me │   ├── __i...


Using Import in Python open another Python script only works one time around

I'm just playing around with some stuff in Pygame, making a little game. I decided to make a separate menu script and a main game script, and I'm using import script2 In the first script, then import script1 In the second one, so that when you press a button in the first, it opens the second, and closing the second opens the first. It works the fir...


How to import a python 2.7 file into a python 3.5 file

Currently, our group is working on building an GUI for our platform. We used pyqt5 so that we make our code python 3.5. However, when we want to add other group's function to our code, it turns out that they are using some packages that only supported in python 2.7. So my question is, how can we import their files into our file, so that both can work properly?


"from gtts import gTTS" works fine in python 2.7 but it does not work in python 3.5. Why?

I want to execute this code: from gtts import gTTS tts = gTTS('hello', lang='en') tts.save('hello.mp3') In python (python 2.7.13) works fine but in python3 (python 3.5.3) is not working. It has always worked in the old python. Now, on a new PC (a raspberry) I wanted to start using the python3 (3.5.3) so I tried and it didn't work. As it was a new installation, the gtts mayb...


Import python file into another python file

Before this is marked as duplicate please read the full problem. So I have a folder structure like this: main.py | |_one |_ one.py |_ file.txt What i'm doing is, importing one.py into main.py and calling a function. My py files are, main.py import one one.f1('test') ...


Cannot import numpy in Python 3.7 or Python 3.8 - Ubuntu 18.04

I manage a group of users so I'm trying to figure out how I can install numpy for all of them to use without having everyone install the package themselves. I have Python 2.7.17 and Python 3.6.9 (installed by default through Ubuntu 18.04). Additionally, I have installed Python 3.7.5, Python 3.8.0, and numpy using the following. sudo apt ...


Time taken by an import in Python

I want to know how much time an import takes for both built-in as well as user defined modules.


How to import python module in a shared folder?

I have some python modules in a shared folder on a Windows machine. The file is \mtl12366150\test\mymodule.py os.path.exists tells me this path is valid. I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid). When I try to import mymodule I get an error saying the module doesn't exist. Is there a way to import module that are located in...


import - Python module seeing a full list as empty in another module

I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module. It's not that the variable can't be read, it just sees an empty list instead of what it really is. Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a sk...


import media does not work in Python

I am reading a book about python. There is a sample. The first line is: import media I am trying to do the same, but the error like below Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; import media ImportError: No module named media I want to know, is the media a default library? Best Regards,


import woes in python

I'm super new on python and i am just deploying an open source app that was done in python and I'm getting a: ImportError: cannot import name DataSource on from django.contrib.gis.gdal import DataSource However, this is just fine: import django.contrib.gis.gdal My current environment setup is: Linux Python 2.7 installed in /opt/python


from a import b in python 2.4

Need help with import in python 2.4 The problem statement is: src\ __init__.py main.py dirFoo\ __init__.py Foo.py dirBar\ __init__.py Bar.py I need to access main.py in Foo.py The version of python is 2.4.3. Its much easier in python > 2.5. But I am a hard time in 2.4


What is the best way to deal with import cycle in Python?

In our projects we have level 'controls' with the following modules: 'grid', 'gridcell', 'combo' and etc. Grid module imports gridcell module since grid consists of cells, while any cell can contain combo inside it. So initially we starting to use 'from ... import ...' statements inside these classes the following way: #grid.py from controls.gridcell import cell #gridcell.py from controls.combo import combo...


pygtk - Cannot Import GST in Python

I'm in a quandary. I'm following the following tutorial (specifically, 6.4.2) http://majorsilence.com/pygtk_audio_and_video_playback_gstreamer I'm running Python 2.7, PyGTK 2.24, and GStreamer WinBuilds 10.7 (the main installer and the SDK). When I try and compile the program, I get the following error:...


post import hooks in python 2.7

According to PEP 369, post import hooks should be implemented for python 2.6 and 3.0. However, I am unable to register or execute any import hook (according to PEP) in python 2.7. Am I missing something ?


How to Break Import Loop in python

I have a situation where there two related large python classes and hence i have put them in separate files. Let say classes are Cobra and Rat. Now need to call methods of Rat from methods of Cobra and vice versa. For this i need to import Cobra in Rat.py and Rat in Cobra.py This creates an import loop and gives an error. Cant import Cobra inside Cobra. How to fix this?? Cobra.py


import - HTML parser in Python

Closed. This question does not meet Stack Overflow guid...


Cannot import SQLite with Python 2.6

I'm running Python 2.6 on Unix and when I run the interactive prompt (SQLite is supposed to be preinstalled) I get: [root@idev htdocs]# python Python 2.6 (r26:66714, Oct 23 2008, 16:25:34) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sqlite T...


Time taken by an import in Python

I want to know how much time an import takes for both built-in as well as user defined modules.


How to import python module in a shared folder?

I have some python modules in a shared folder on a Windows machine. The file is \mtl12366150\test\mymodule.py os.path.exists tells me this path is valid. I appended to sys.path the folder \mtl12366150\test (and os.path.exists tells me this path is valid). When I try to import mymodule I get an error saying the module doesn't exist. Is there a way to import module that are located in...


import - Python module seeing a full list as empty in another module

I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module. It's not that the variable can't be read, it just sees an empty list instead of what it really is. Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a sk...


import media does not work in Python

I am reading a book about python. There is a sample. The first line is: import media I am trying to do the same, but the error like below Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; import media ImportError: No module named media I want to know, is the media a default library? Best Regards,


java - import os to j2me

I am trying to write this code to j2me. Does anyone has any idea how to do this? Thanks! import os if os.path.isfile("c:\\python\\myfolder\\test.txt"):


Puppy Linux - import gtk throws error in Python

I am using Linux version 2.6.24.16. I believe it is using Puppy Linux 4.2. I am actually using Puppy Arcade, which is a specialized branch. Their help file hints that it is 4.2, however. I am using Python 2.6.4 which I installed through a puppy package released here: http://code.google...


How do I import a third party module in Python?

I've found a third party module which I would like to use. How do I technically import that module? Particularly, I want to use a module called context_manager. obviously, I cannot just import garlicsim.general_misc.context_managerbecause it won't find


import - Refer to a Module within the Module in Python

I have a directory structure for a module like the following: - foo - __init__.py - gui.py I use the foo module from other places. Now I want to use something from the foo module in gui.py, but when I try to, I get this: jsternberg@aquila:~$ python foo/gui.py Traceback (most recent call last): File "foo/gui.py", line 3, in &lt;module&gt; import foo ImportError:...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top