I'm trying to write a program that is related to another program, so how can I access the individual functions from my previous program and work with them as required, I know you are suppose to import that program but what to do after that.
The program that I import how can I use functions from it.
It would be better if you write code.
I assume your 1st code is code1.py and you want to use fun1 from it in code2.py.
Put them in same directory . . .
Use:
import code1
code1.fun1()
Or
from code1 import *
fun1()
Note: 2nd method is not recommended.
If you want to import it from another folder you should also try to use os.chdir().
But mostly you can use either import * to import all of the functions or just import and then the functions you want to import.
Related
My question is very simple. I have a piece of code that I want to reuse, 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 file code1.py:
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 beginner in Python, so this will help me a lot in the future, thanks.
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
This lesson is good to understand imports in python: https://realpython.com/python-import/
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.
The code showed below is based on the fact that files code1.py and code2.py are in the same directory.
Solution 1
In this code I have changed only your import instruction in code2.py:
from code1 import a
b = a + 1
print(b)
Solution 2
In this solution I don't have changed your import instruction in the file code2.py, but I have used the module name (code1) to refer to a variable. In this case it is used the access notation moduleName.variableName.
So the file code2.py becomes:
import code1
b = code1.a + 1
print(b)
This means that in this case code1.py is used as a Python module and not as a script (the difference between script and module could be the topic of an other question).
Python namespace
In Python terminology the moduleName is the namespace defined by the module. By the namespace (that is the name placed after the import instruction) you can access to the objects content inside the module by the syntax namespace.object.
The interpreter creates a global namespace for any module that your program loads with the import statement.
About namespace useful this link of realpython.
The Issue:
I want to use a module that has been imported from within a different module with it's function.
What I want to achieve:
main.py
import differentFile
print (differentFile.functionName.os.getcwd())
differentFile.py
def functionName():
import os
What I have tried:
Pretty much the above, but it doesn't work as functionName as no function os.
I have managed to achieve the above without using the function, but I need to use the function.
There is no reason to do this, you can simply import os in main
I have several python scripts that all start with the same set of lines, and I would like to be able to change the lines only once.
For example something like this:
import pickle
import sys
sys.path.append("/Users/user/folder/")
import someOtherModules
x=someOtherModules.function()
I know I could save this as a string, and then load the string and run the exec() command, but I was wondering if there is a better way to do this.
In other words, I want to import a list of modules and run some functions at the beginning of every script.
You can define your own module.
# my_init.py
def init():
print("Initializing...")
And simply add this at the beginning of all your scripts:
import my_init
my_init.init()
Depending on where your scripts and my_init.py are located, you may need to add it to your Python user site directory, see: Where should I put my own python module so that it can be imported
You can move all stuff in separate script and in another scripts import everything from it: from my_fancy_script import *. In this case not only code inside my_fancy_script will be executed but also imports will be pushed to another files.
Anyway, better to use Delgan's answer
The question is pretty simple: I need to move a piece of my code to the another file. In the main file, I'll do something like import not_main. Is is possible to run imported code as a part of the main file? Here's a simplified example:
__code
\__main.py
|__not_main.py
main.py content:
a = 5
import not_main
not_main.py content:
print a
When I'm running main.py, there is a error : NameError: name 'a' is not defined. How can I make it work? Thanks for any tips.
It's not possible to directly reference a variable in one module that's defined in another module unless you import that module first. Doesn't matter that it's the main module, this error would happen if you tried to do the same between any two modules. An imported module does not gain the scope of the module it's imported into.
There are possible workarounds, though I would caution using them if the code you're trying to separate out is fairly complex. But if you're intent on doing it, I'd suggest separating out any variables needed in both modules into a third module that only contains those variables. So the simple example you gave would turn into this:
cross_module_variables.py:
a = 5
main.py:
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
For more complex code you might need to assign the value of the variable in main after doing executing some code to produce the value. In that case you'll want to import cross_module_variables into the main module and assign a value to it. Course that variable has to be instantiated before it can be used in main so you'll have define the variable in cross_module_variable with some default value. So it would look something more like this:
cross_module_variables.py:
a = 0
main.py:
import cross_module_variables as cmv
cmv.a = 5
import not_main
not_main.py:
import cross_module_variables as cmv
print cmv.a
See this answer for more info on cross module variables.
With all that said, I would highly suggest you look at restructuring your code in some other sane way. It sounds like you're running all your code straight in modules instead of defining functions around discrete sections of code. You should look into ways of designing coherent functional programs.
I understand how to actually link python files, however, i don't understand how to get variable's from these linked files. I've tried to grab them and I keep getting NameError.
How do I go about doing this? The reason i want to link files is to simply neaten up my script and not make it 10000000000 lines long. Also, in the imported python script, do i have to import everything again? Another question, do i use the self function when using another scripts functions?
ie;
Main Script:
import sys, os
import importedpyfile
Imported Py File
import sys, os
I understand how to actually link python files, however, i don't
understand how to get variable's from these linked files. I've tried
to grab them and I keep getting NameError.
How are you doing that? Post more code. For instance, the following works:
file1.py
#!/usr/bin/env python
from file2 import file2_func, file2_variable
file2_func()
print file2_variable
file2.py:
#!/usr/bin/env python
file2_variable = "I'm a variable!"
def file2_func():
print "Hello World!"
Also, in the imported python script, do i have to import everything
again?
Nope, modules should be imported when the python interpreter reads that file.
Another question, do i use the self function when using another
scripts functions?
Nope, that's usually to access class members. See python self explained.
There is also more than one way to import files. See the other answer for some explanations.
I think what you are trying to ask is how to get access to global vars from on .py file without having to deal with namespaces.
In your main script, replace the call to import importedpyfile to say this instead
from importedpyfile import *
Ideally, you keep the code the way you have it. But instead, just reference those global vars with the importedpyfile namespace.
e.g.
import importedpyfile
importedpyfile.MyFunction() # calls "MyFunction" that is defined in importedpyfile.py
Python modules are not "linked" in the sense of C/C++ linking libraries into an executable. A Python import operation creates a name that refers to the imported module; without this name there is no (direct) way to access another module.