I have couple questions regarding running code from multiple files from one .py file
When I import the Files with
from [subfolder] import [First scriptname - without .py]
from [subfolder] import [Second scriptname - without .py]
the scripts start running instantly, like if my scripts have a print code it would look like this after running the combined-scripts file
print("Hi Im Script One")
print("Hi Im Script Two")
now I could put them in functions and run the functions but my files also have some variables that are not inside functions, the question I have is if there is a way to not start the script automatically after import?
Also what happens with variables inside these scripts, are they usable throughout the combined file or do i need to state them with something like "global"?
is there a way to not start the script automaticly after import?
This is what python's if __name__ == "__main__": is for.
Anything outside that (imports, etc.) will be run when the .py file is imported.
what happens with variables inside these scripts, are they usable troughout the combined file or do i need to state them with something like "global"?
They may be best put inside a class, or you can also (not sure how Pythonic/not this is):
from [FirstScriptName_without_.py] import [className_a], [functionName_b], [varName_c]
Related
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()
This question already has answers here:
How can I make one python file run another? [duplicate]
(8 answers)
Closed 2 years ago.
I have a list of .py file that I need to run sequentially.
I usually do it manually, one by one.
Anyway I'd like to have a .py file by which I run these .py automatically.
In R I usually use the command source:
Source (file1, file2 etc)
Is there a way to do anything similar in python?
By the way, I use IDLE, so I'd like to have a solution using this program.
Thank you in advance
execfile(filename)
is probably what you want to use
for instance if you have a list of files to run
e.g.
files_to_run = ["path_to/File1", "path_to/File2", "path_to/File3", "path_to/File4"]
for file in files_to_run:
execfile(file)
simple import technically executes the file.
In python, it is common practice to use to define all the required functions int he module and function calls are defined inside if __name__ == "__main__": [means the code inside the if will execute only if the script called directly not when imported]
so that the same module can used as executable and also imported in another file.
Technically, if you did not use if __name__ == "__main__": in your files, simply import itself will execute them.
So I'm new to Python and I need some help on how to improve my life. I learned Python for work and need to cut my workload a little. I have three different scripts which I run around 5 copies of at the same time all the time, they read XML data and add in information etc... However, when I make a change to a script I have to change the 5 other files too, which is annoying after a while. I can't just run the same script 5 times because each file needs some different parameters which I store as variables at the start in every script (different filepaths...).
But I'm sure theres a much better way out there?
A very small example:
script1.py
xml.open('c:\file1.xls')
while True:
do script...
script2.py
xml.open('c:\file2.xls')
while True:
do exactley the same script...
etc...
You'll want to learn about Python functions and modules.
A function is the solution to your problem: it bundles some functionality and allows you to call it to run it, with only minor differences passed as a parameter:
def do_something_with_my_sheet(name):
xml.open(name)
while True:
do script...
Elsewhere in your script, you can just call the function:
do_something_with_my_sheet('c:\file1.xls')
Now, if you want to use the same function from multiple other scripts, you can put the function in a module and import it from both scripts. For example:
This is my_module.py:
def do_something_with_my_sheet(name):
xml.open(name)
while True:
do script...
This is script1.py:
import my_module
my_module.do_something_with_my_sheet('c:\file1.xls')
And this could be script2.py (showing a different style of import):
from my_module import do_something_with_my_sheet
do_something_with_my_sheet('c:\file2.xls')
Note that the examples above assume you have everything sitting in a single folder, all the scripts in one place. You can separate stuff for easier reuse by putting your module in a package, but that's beyond the scope of this answer - look into it if you're curious.
You only need one script, that takes the name of the file as an argument:
import sys
xml.open(sys.argv[1])
while True:
do script...
Then run the script. Other variables can be passed as additional arguments, accessed via sys.argv[2], etc.
If there are many such parameters, it may be easier to save them in a configuration file, the pass the name of the configuration file as the single argument. Your script would then parse the file for all the information it needs.
For example, you might have a JSON file with contents like
{
"filename": "c:\file1.xls",
"some_param": 6,
"some_other_param": True
}
and your script would look like
import json
import sys
with open(sys.argv[1]) as f:
config = json.load(f)
xml.open(config['filename'])
while True:
do stuff using config['some_param'] and config['some_other_param']
I want to make my own programming language based on python which will provide additional features that python wasn't provide, for example to make multiline anonymous function with custom syntax. I want my programming language is so simple to be used, just import my script, then I read the script file which is imported my script, then process it's code and stop anymore execution of the script which called my script to prevent error on syntax...
Let say there are 2 py file, main.py and MyLanguage.py
The main.py imported MyLanguage.py
Then how to get the main.py file from MyLanguage.py if main.py can be another name(Dynamic Name)?
Additional information:
I using python 3.4.4 on Windows 7
Like Colonder, I believe the project you have in mind is far more difficult than you imagine.
But, to get you started, here is how to get the main.py file from inside MyLanguage.py. If your importing module looks like this
# main.py
import MyLanguage
if __name__ == "__main__":
print("Hello world from main.py")
and the module it is importing looks like this, in Python 3:
#MyLanguage.py
import inspect
def caller_discoverer():
print('Importing file is', inspect.stack()[-1].filename)
caller_discoverer()
or (edit) like this, in Python 2:
#MyLanguage.py
import inspect
def caller_discoverer():
print 'Importing file is', inspect.stack()[-1][1]
caller_discoverer()
then the output you will get when you run main.py is
Importing file is E:/..blahblahblah../StackOverflow-3.6/48034902/main.py
Hello world from main.py
I believe this answers the question you asked, though I don't think it goes very far towards achieving what you want. The reason for my scepticism is simple: the import statement expects a file containing valid Python, and if you want to import a file with your own non-Python syntax, then you are going to have to do some very clever stuff with import hooks. Without that, your program will simply fail at the import statement with a syntax error.
Best of luck.
I have this script:
from myhelperfunctions import *
# parse arguments
args = docopt(__doc__, version='mainprog 1.0')
myhelper1(args)
...
This is a script someone else maintains and I have no control over, so i cant modify it. The script structure looks like
/opt/app-to-import/{main.py, myhelperfunctions.py}
I want to run this code in another program in my home directory, but don't want to start a new process. so I tried exec() and imp.load_source() to load and run it inside the same process. But every time it complains saying no module named myhelperfunctions. What is the right way to do this? I am using python2.7.