I'm trying to import two modules so that they run after each other. Here is my code:
from Game import *
main()
from Typing_Question_Screen import *
When I run my code, the Game module loads first but if I close the file, the Typing_Question_Screen module is loaded too. But once the Game module finishes, nothing loads next.
How can I run these two right after each other so that when the Game file ends, the Typing_Question_Screen loads too? Thank you.
From my understanding you have two files:
file1.py
file2.py
If you want to run file.1py and then run file2.py without having to manually do it, there are multiple ways. I would recommend creating a batch.
So you have your two .py files. You will want to create a new file. Don't worry about the extension. We will take care of that later. Navigate to your terminal at the bottom and type in where python. That is the first thing you will put in the double quotes. The next is where your file1.py file is located. You will do the same for file2.py indicated in picture 5. You can use the pause function to pause the process. So after file1.py and ran you will be promted to start file2.py. If you don't want to be prompted, then just remove the pause. You then need to navigate to your file explore to where the batch file was created. In my case it is here (picture 6). Right click on the batch file and select rename. Add .bat at the end. That will convert it to the batch file. Then when you run it (doubleclick). The two .py files that we set up in the batch will run!
The statements in the global scope of imported modules are executed when they are imported. So, you may consider adding function calls or other desired statements in the global scope. Let me give an example:
Game.py:
def main():
print("game")
main()
Typing_Question_Screen.py:
def test():
print("tqs")
test()
The importing file:
from Game import *
from Typing_Question_Screen import *
print("import complete")
The output of this file would be:
game
tqs
import complete
Note that you can check whether the module is being executed independently. (Please keep in mind that usually the opposite of this behavior is used, and generally imports are not expected to execute code by themselves.)
For example, the below implementation calls main only if the module is being imported:
def test():
print("tqs")
if __name__ != __main__:
test()
__name__, a special variable of the module set by the interpreter, is __main__ when the module is run without being imported.
Also, I would avoid importing with *. Moreover, the imports should be at the top of the importing file, separated from other statements and definitions. See: PEP8 on importing
I think you may modify your code as:
import Game
import Typing_Question_Screen
Game.main()
Related
I have the program, which does stuff. And it counts how many times it has done some things by day and by hour. So I created a class and assigned it to hourly and daily.
And besides that, I have a multi thread function (let's call it background) which is used for the menu in the console. It is used to see/print or even modify variables. But it doesn't work. Every time I want it to print the class attributes, it always prints 0 for all attributes. How to fix this?
I also have this class and functions in separate modules
module a:
class Data():
def __init__(self,some_count):
self.some_count=some_count
daily=Data(0)
hourly=Data(0)
module b:
from a import daily,hourly
def print_data(command):
if command == "daily" :print(f"Daily saying hi is: {daily.some_count}")
if command == "hourly" :print(f"Hourly saying hi is: {hourly.some_count}")
background(): #It is used for menu. Depending on what you want, it can also print class attributes
while True:
print_data(input()) #you need to choose the command
module c:
from a import daily,hourly
from b import background
threading1 = threading.Thread(target=background) #
threading1.daemon = True #
threading1.start() #these 3 lines are copy pasted from my code
#this is the main function. And if you insert print(hourly.some_count) it will print the right value
while True:
hourly.some_count+=1
daily.some_count+=2
time.sleep(10000)
Note, this is not my code. Well it is, but just the idea. The above code is not functional, i just wanted to show, how i coded it.
I just don't know, why the function to print doesn't work. I assume that the "daily" and "hourly" class are mutated for a thread?
Perhaps it is a problem with imports? I have defined a class in module a, imported the "daily" and "hourly" in class b where I used in function. And then imported that function into module c where the main program is?
Thank you for help
EDIT, FOR THOSE WHO WANT AN ANSWER:
the solution below did not help.
I found a mistake myself later on and fixed it this way:
I made a seperate module, where i declared all the variables and classes. Only declaragion, no fuctions or any off that. And then i imported a varible or clas like this: From "class_declaration" import "name of class"
That way i can share the variable accros modules and threads
your concepts are correct: instance attributes changed in one thread should be visible in another thread. What I think might be wrong in your setup has to do with module naming and importing: some of the imports are ending internally as "myproject.a" and others just as "a": internally Python will create separate modules and separate objects.
If you uniformize the module names and containing directory in a Python package, everything should work as expected.
Try this: put all your .py modules in a folder containing an empty (0 bytes) file named __init__.py - and write your entry-point (the code from which your program will start running) in a file named __main__.py. Rewrite your imports to read from .a import daily, hourly (see the ".") -
and then from the parent of that directory, run the project with python -m <directory_name> - Python should execute the code in __main__.py and see all the other modules as part of the same package.
I am new to python and trying out my own pet project. So, my project directories look like this:
Now in my main.py file I have imported models module
from models.eq_melting import * from models.frac_melting import *. After that I put some print statements :
Now the problem is whatever function that is residing in files of module models, is getting executed first rather than the print statements.
Please help me to understand why this is happening.
When you import a module you are in fact executing it, so every statement in the module will get run. If it is just function defs then you will just add those functions to the namespace, but not actually run the code they contain. However if it contains print or other statements then they will get executed.
To summarise when you import a module you execute everything in that module.
This is also why you see very often code that looks like
if __name__ == "__main__" at the bottom of many modules. If the module gets imported the if condition won't be satisfied, but if the module is executed directly as a script then the if condition will be satisfied and the code will run.
As a side note you should do your best to avoid from module import * - it will make debugging ten times harder as it makes it impossible for the computer (and the human) to know where items in its name space came from.
I have a program which involves several classes as frames in tkinter. I have a separate file that uses pygame and is a chess game. I want to be able to load this file up and execute it when I press a certain tkinter button in one of the frames and to then close this file. I am aware that importing the module at the beginning of the tkinter file runs it immediately which is not what I need. I only want it to run when the button is pressed.
I have attempted to use other modules which do not work. I have tried using functions which also did not work.
I expect to be able to run the chess file when the button is pressed, instead of immediately as this holding file is ran.
However, when run the chess file executes immediately and this other file does not even run.
If you want to open the file in the native editor, the same as double clicking on windows,
you could call os.startfile(file). That runs the file.
Example:
os.startfile('C:\\Windows\\System32\\notepad.exe')
That would run notepad.
Although I wouldn't recommend doing so, you can make a function that will import a module after you press the button as follows:
Button(command=my_func)
def my_func():
import foo, bar
However, if you simply do not wish to run functions from a foreign file, put the following code in the file:
if __name__ == "__main__:
<Code that gets run>
And simply call the function you wish to call:
import bar
bar.foo()
Note that importlib is the better option for importing external files.
If you enclose your main Python code in if __name__ == "__main__":, then it will run only if the file is executed, not loaded as the module. It's a common practice.
And if you make your spam.py like that:
def main():
do_things_here
if __name__ == "__main__":
main()
You can just import spam at the beginning with nothing happening and do spam.main() when you want to execute it.
But if you really want to load modules dynamically, exec("import " + module_name)
I have 2 python files. file1.py and file2.py
file1.py
print "file1"
file2.py
import file1
print "file2"
and when i run file2,the output is
file1
file2
The question may seem little naive but i want to know what exactly is happening here.
Thanks in Advance.
Yes.
When importing a file it is being run.
To avoid this, file1.py can be:
if __name__=='__main__':
print 'file1'
And then the text will be printed only if file1.py is the main file being run directly.
In a sense yes. When you import a file, you will run all the script and you will also initialize all the methods.
To ensure that code is only run when the file is run directly and not when it is imported. You should put all your main code in main() and do it as:
def main():
#all your main code here
if __name__ == '__main__':
main()
The import statement combines two operations; it searches for the named module, then it binds the results of that search to a name in the local scope. The search operation of the import statement is defined as a call to the import() function, with the appropriate arguments. The return value of import() is used to perform the name binding operation of the import statement. See the import statement for the exact details of that name binding operation.
import file using python
To print 'file2' your code, you need to pass it as a command to the Python interpreter,
python myscript.py
there's no main() function that gets run automatically, so the main() function is implicitly all the code at the top level, and call if __name__ == "__main__"
How main does in python
Python won't allow me to import classes into eachother. I know there is no "package" solution in Python, so I'm not sure how this could be done. Take a look at my files' codes:
file Main.py:
from Tile import tile
tile.assign()
class main:
x = 0
#staticmethod
def assign():
tile.x = 20
file Tile.py:
from Main import main
main.assign()
class tile:
x = 0
#staticmethod
def assign():
main.x = 20
I get the error "class tile can not be imported".
If file A imports file B, and file B imports file A, they would keep importing each other indefinitely until the program crashed.
You need to rethink your logic in a way that doesn't require this circular dependency. For example, a 3rd file could import both files and perform both assignments.
You have your import backwards and the from needs to have the name of the module
from Tile import tile
Python begins executing Main.py. It sees the import, and so goes to execute Tile.py. Note that it has not yet executed the class statement!
So Python begins executing Tile.py. It sees an import from Main, and it already has that module in memory, so it doesn't re-execute the code in Main.py (even worse things would go wrong if it did). It tries to pull out a variable main from the Main module, but the class statement binding main hasn't executed yet (we're still in the process of executing the import statement, advice that line). So you get the error about there not being a clsss main in module Main (or Tile, if you started from there).
You could avoid that by importing the modules rather than importing classes out of the modules, and using qualified names, but then you'd fall one line down when Main.main doesn't work. Your code makes no sense I'm a dynamic language; you can't have both the definition of class main wait until after tile.assign has been called and the definition of class tile wait until after main.assign has been called.
If you really need this circular dependency (it's often, but not always a sign that something has gone wrong at the design stage), then you need to separate out "scaffolding" like defining classes and functions and variables from "execution", where you actually call classes and functions or use variables. Then your circular imports of the "scaffolding" will work even though none of the modules will be properly initialized while the importing is going on, and by the time you get to starting the "execution" everything will work.