I have 2 scripts.
Main.py
Update.py
I have a function in Main.py which basically does the following:
def log(message):
print(message)
os.system("echo " + message + " >> /logfile.txt")
And in the Update.py file I have a single function which basically does the update. However throughout the update function, it calls "log(message)" with whatever the message is at that point.
The problem now though is I'm getting a NameError: global name "log" is not defined whenever I try use the function outside of the Main.py script.
Any help? on how I would be able to use the function 'log' wherever?
*Code simplified for explanation.
EDIT:
Main.py imports Update from /Scripts/Update.py
Update.py imports log from Main.py
When i try this, it fails saying "cannot import name Update"
Don't import log from Main. That'll rerun the code in Main.py, since running Main.py as a script and importing it as a module aren't equivalent. Other modules should not depend on functions defined in the main script. Instead, put your log function in another module and import that, or have Main.py explicitly pass a logger to the other modules somehow.
Update: You can't import Update because Python can't find it. Python checks in 4 places for modules to import, but the ones you should be interested in are
the directory the script was from, and
the directories specified in the PYTHONPATH environment variable.
You'll either need to put Main.py and the things it imports in the same directory, or add /Scripts to your PYTHONPATH.
Just add in Update.py the line
from Main import log
and you will be able to call log() from Update.py.
You should import the function:
from Main import log
Or best:
import Main
Main.log()
For modules importing each other, refer How can I have modules that mutually import each other.
Related
I have a moveslist.py file with function movesSelection and a main.py file. Within my main.py, I've made sure that my variables are set to global and I had another function makeNewChar. Within makeNewChar, I'm trying to call movesSelection but I get "NameError: name 'movesSelection' is not defined.
Since my moveslist.py uses some global variables from main, I imported main into the file.
For my main.py, I did from moveslist import *. I also tried import movesList and from moveslist import movesSelection. All of those threw back errors.
How can I use movesSelection within my main.py?
There may be a few different reasons but some of the most common are having a file with the same name or likely the file you are looking for is in another directory so i will show you my correct here
[Edit] You should remove the .py when importing example below
## This is "main.py" keep that in mind when viewing
## Change line 4 to import and the python file as Func = Func.py in this context
import Func
Func.Activate()
## This is "Func.py"
class Activate:(
print("Hello World!")
)
Or you may need to do as says below!
##Include file extension and move the file with the folder in the correct space and i'd appreciate it if you'd be so kind to mark this question as correct
import movesSelection.py
Add "from moveslist import movesSelection" into makeNewChar.
You do not have to add the .py suffix when you import.
Instead of creating a module.py (containing all the functions), can I create a folder MODULE and collect all the functions in different files?
I'd like to do that in a way that main.py contains import MODULE and, if it's possible, to call the functions directly (fun_1(), fun_2()) without the nomenclature MODULE.fun_1(), MODULE.fun_2(), etc.
I think the only right way is creating __init__.py (import all functions contained in other files) in your MODULE folder. And use statement from MODULE import *. If you wanna use import MODULE and call func in other files then, that never work. Interpreter will raise the NameError, cause there are no the variables.
__init__.py file like this:
from file1 import func_1
from file2 import func_2
Yes.
Create your main file, main.py along with another file where you want to put another function. I will use the other.py file.
In main.py, write
from other import *
Note the missing .py, Python handles that for you.
In other.py, write
def your_function():
return -1
You can have as many functions in here as you want. Now, you can call your_function() in main.py.
Example Repl.it: https://repl.it/repls/MeaslyBurdensomeDesigners
I have a Python script which is calling a class of another Python script.
The structure of these two scripts are as follows:
c:\testing\sample.py
c:\testing\example\demo\projects\module.py
Now inside sample.py I am calling module.py as follows:
from "c:/testing/example/demo/projects/module.py" import module_C
When I execute this portion of sample.py I get an error There is an error in program and this error occurs in its first line only.
How shall I call the module_C inside sample.py?
the from/import syntax does not work with files, only with modules.
To achieve what you want, there are 2 possibilities
first one: turn traversing directories into modules:
create empty __init__.py files in c:/testing/example/demo, and c:/testing/example/demo/projects,
then from demo.projects.module import module_C
second one: add path dynamically:
import sys,os
sys.path.add(os.path.join(os.path.dirname(__file__),"demo/projects"))
from module import module_C
knowing where you are running, use current module directory and add the demo/projects absolute path: it works because the paths have a common prefix)
i need to call a function from from one python class to another which are at different directories.
I'm using Eclipse and PyDev for developing scripts.
sample.py
class Employee:
def meth1(self,arg):
self.arg=arg
print(arg)
ob=Employee()
ob.meth1("world")
main.py
class main:
def meth(self,arg):
self.arg=arg
print(arg)
obj1=main()
obj1.meth("hello")
I need to access meth1 in main.py
updated code
main.py
from samp.sample import Employee
class main:
def meth(self,arg):
self.arg=arg
print(arg)
obj1=main()
obj1.meth("hello")
After executing main.py it is printing "world" automatically without calling it.
my requirement is i need to call meth1 from main.py explicitly
please find my folder below
import is the concept you need here. main.py will need to import sample and then access symbols defined in that module such as sample.Employee
To ensure that sample.py can be found at import time, the path to its parent directory can be appended to sys.path (to get access to that, of course, you will first need to import sys). To manipulate paths (for example, to turn a relative path like '../samp' into an absolute path, you might want to import os as well and take a look at the standard library functions the sub-module os.path has to offer.
You will have to import the sample.py file as a module to your main.py file. Since the files are in different directories, you will need to use the __init__.py
From the documentation:
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.
Here is a related stack overflow question which explains the solution in more detail.
It's generally not a good idea to alter the sys.path variable. This can make scripts non-portable. Better is to just place your extra modules in the user site directory. You can find out what that is with the following script.
import os
import sys
import site
print(os.path.join(site.USER_BASE, "lib", "python{}.{}".format(*sys.version_info[0:2]), "site-packages"))
Place your modules there. Then you can just import as any other module.
import sample
emp = sample.Employee()
Later you can package it using distutils or setuptools and the imports will still work the same.
I am trying out the answer in this.
The __init__.py file in a folder named MyLibs contains:
LogFile = r'D:\temp'
In utils.py in the same folder MyLibs, I tried various ways to access the LogFile variable:
from __init__ import *
print LogFile #Gives: NameError: name 'LogFile' is not defined`:
and:
import __init__
print MyLibs.LogFile #Gives: NameError: name 'MyLibs' is not defined
I got the errors while executing from MyLibs.utils import *
What is the fix I must do? I prefer a method where I can reference LogFile directly without having to add namespace prefixes.
My mistake.
The updated __init__.py was somehow not executed. I started a new Python session and it worked.
Sorry for the false alarm.
Not sure how to do this with 2.7's implicit relative imports, but you could try this:
from __future__ import absolute_import
from . import LogFile
If you're running the Python module directly, you need to run it with python -m MyLibs.utils rather than python MyLibs/utils.py.