I'm trying to import the User class from a file called gui.py into another called snake.py. I want to import the class so that I can use ,a method within the class and an instance of the class called current_user. But when I do:
from gui import User
It imports everything from gui.py. Does anyone know where I've gone wrong and what I can do to fix this?
I'm new to working with multiple files in Python and this is quite confusing to me.
The files for this are available at:
https://github.com/VladRadoi08/Snake-LoginUI
Thanks!
Anything in the file you import will be run. To prevent this, try putting all the code you don't want to run within this conditional:
if __name__ == "__main__":
That will ensure it only runs if you actually run the python file instead of importing it.
Related
I'm trying to use multiple files in my programing and I ran into a problem.
I have two files: main.py, nu.py
The main file is:
import numpy
import nu
def numarray():
numpy.array(some code goes here)
nu.createarray()
The nu file is:
def createarray():
numpy.array(some code goes here)
When I run main I get an error:
File "D:\python\nu.py", line 2, in createarray
numpy.array(some code goes here)
NameError: name 'numpy' is not defined
numpy is just an exaple, I'm using about six imports.
As far as I see it, I have to import all moduls on all files, but it creating a problem where certain modules can't be loaded twice, it just hang.
What I'm doing wrong and how can I properly import functions from another file while using imported modules from the main file?
I hope i explain it well.
thanks for helping!
I have years in python and importing from other files is still a headache..
The problmen here is that you are not importing numpy in "nu.py".
But as you say sometimes it's a little annoying have to import al libraries in all files.
The last thing is, How do you get the error a module cannot be imported twice? can you give me an example?
In each separate python script if you are using a module within you need to import it to access. So you will need to 'import numpy' in your nu.py script like below
If possible try keeping the use of a module within a script so you dont have import the same multiple times, although this wont always be appropriate
I have two Python files, global.py and test_train.py, both sitting in the same folder. I am trying to allow test_train.py to access everything (functions, variables, etc. in global.py). I cannot get it to work. In the same folder is init.py. I have tried import global and have also referenced Source a Python's file from another Python file, but nothing seems to work. Suggestions?
You should change your file (global.py) name, when you import global.py,
the module name global will conflict with python keyword global
import global # global is keyword in python, you should avoid using this name
# so it will occur error
import global_test # this line is OK, if your .py name is global_test
Typically import global should work.
However, if it doesn't work, you should do a check to see if the import is happening successfully.
A print statement at the end of the global.py script should suffice to tell you so.
Otherwise, if the import is working, then you should try changing your code by encapsulating the entire contents of the global.py in a class, and then creating an object of that class in your test_train.py script to call its functions and attributes.
You can also make use of getattr function to call directly from global.py
I am using Python 2.7 on Windows 7 Professional.
I am trying to call a function saved in another file to run in this file's code.
Function called dosomething is found in anotherfile.py
anotherfile.py is in the same directory as current code.
My call in this file is simple:
import anotherfile
print anotherfile.dosomething
I am getting an error: No module named anotherfile
The problem is the same as I found in this post
I don't understand the solution but I'd like any insight?
Thank you.
EDIT: The other question/answers discuss resetting CLASSPATH and setting PYTHONPATH. I explored this but was not sure how to do this. Perhaps relevant?
Let us have two files in the same directory. Files are called main.py and another.py.
First write a method in another.py:
def do_something():
return "This is the do something method"
Then call the method from main.py. Here is the main.py:
import another
print another.do_something()
Run main.py and you will get output like this:
This is the do something method
N.B.: The above code is being executed using Python 2.7 in Windows 10.
Specify the module then the file then the import like so:
from this_module.anotherfile import dosomething
or if you want all functions from "anotherfile.py"
from this_module.anotherfile import *
and then you can call the "dosomething" command without the "anotherfile" prefix.
I ran into same problem. After ample of trials, I ended up solving it with the below mentioned solution:
Make sure your current file and anotherfile.py lies in same location of system path.
Say your another.py and current file lies at location : "C:/Users/ABC"
In case, one is not aware of system path. Use below code in current file:
import sys
print(sys.path)
import sys
sys.path.append('/C:/Users/ABC/')
Then you do below code in same current code:
from another import dosomething
I found the issue. Python was looking in another directory for the files. I explicitly set my working directory as the path to where thisfile.py and anotherfile.py reside and it works. Thank you for all the quick replies.
OK guys I can't find a solution anywhere for my problem, and I hope the solution is a simple one. Previously I had a flat file system for my gae project with no folders. I've been refactoring some code and I tried to put some in a folder. I'm a bit new and I've never done something like this before, but nothing on the internet suggests that I shouldn't easily be able to move my files into a folder. I added the __init__.py file to the folder and I import the folder name from my main program. However when I attempt to access a particular function in one of the files, it chokes and says AttributeError: 'module' object has no attribute 'site1_ripper'
here is my file structure:
main.py
SiteCrawlers\
__init__.py
site1_ripper.py
here are important parts of the files:
main.py
import SiteCrawlers
class Updater(webapp.RequestHandler):
def get(self):
SiteCrawlers.site1_ripper.siteCrawler()
site1_ripper.py
def siteCrawler()
#stuff here
I think the problem is that you need to explicitly import site1_ripper unless it's specified in __init__.py. Make your main import be:
import SiteCrawlers.site1_ripper
In your main file try:
from SiteCrawlers.site1_ripper import siteCrawler
class Updater(webapp.RequestHandler):
def get(self):
siteCrawler()
I'm sorry for the verbal description.
I have a wxPython app in a file called applicationwindow.py that resides in a package called garlicsimwx. When I launch the app by launching the aforementioned file, it all works well. However, I have created a file rundemo.py in a folder which contains the garlicsimwx package, which runs the app as well. When I use rundemo.py, the app launches, however, when the main wx.Frame imports a sub-package of garlicsimwx, namely simulations.life, for some reason a new instance of my application is created (i.e., a new identical window pops out.)
I have tried stepping through the commands one-by-one, and although the bug happens only after importing the sub-package, the import statement doesn't directly cause it. Only when control returns to PyApp.MainLoop the second window opens.
How do I stop this?
I think you have code in one of your modules that looks like this:
import wx
class MyFrame(wx.Frame):
def __init__(...):
...
frame = MyFrame(...)
The frame will be created when this module is first imported. To prevent that, use the common Python idiom:
import wx
class MyFrame(wx.Frame):
def __init__(...):
...
if __name__ == '__main__':
frame = MyFrame(...)
Did I guess correctly?
You could create a global boolean variable like g_window_was_drawn and check it in the function that does the work of creating a window. The value would be false at the start of the program and would change to True when first creating a window. The function that creates the window would check if the g_window_was_drawn is already true, and if it is, it would throw an exception. Then You will have a nice stacktrace telling You who is responsible of executing this function.
I hope that helps You find it. I'm sorry for the verbal solution ;)
Got it: There was no
if __name__=='__main__':
in my rundemo file. It was actually a multiprocessing issue: The new window was opened in a separate process.