Home > front end >  How to run the one python code in another python code
How to run the one python code in another python code

Time:10-18

My question is very simple. I have 1 code that I always use. But I don't want to copy it every time I use it, is there any way I can import it and run it in my main file? for example, in code1.py writes

a=1

I want to run in code2.py

import code1
b=a 1
print(b)

The output says a is not defined. I don't know where I got it wrong. I am a very beginner in Python, so this will help me a lot in the future, thanks

CodePudding user response:

This lesson is good to understand imports in python: https://realpython.com/python-import/

CodePudding user response:

You will need to import the variable from the your Python module to use it.

from code1 import a

The import statement will differ slightly if your modules are not at the same level.

CodePudding user response:

  1. Ensure that the two files are in the same directory.

If this is the case, you can directly import


from filename import variablename/class/function

in your case:


from code1 import a

CodePudding user response:

I suppose that code1.py and code.py are in the same directory. In this case you have to change only the import instruction so it is enough that you change code2.py to the following code:

from code1 import a
b = a   1
print(b)

An other possibility is maintain your import and use the module name when you use the a variable (moduleName.variableName). In your example the file code2.py become:

import code1
b = code1.a   1
print(b)

Python namespace

In Python terminology the moduleName is the namespace defined by the module. By the namespace (after the import instruction) you can access to the objects content inside the module. In fact the interpreter creates a global namespace for any module that your program loads with the import statement.

  • Related