How to sequentially run multiple script in python [duplicate] - python

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.

Related

Python Question about running multiple scripts in one script

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]

Behavior of import in python [duplicate]

This question already has answers here:
Does python optimize modules when they are imported multiple times?
(6 answers)
Closed 3 years ago.
Is it safe to assume that python module is calculated once?
If module A contains CONST_A = json.load(...) and is imported multiple times in different files of the same program and different threads, will it be calculated/executed just once?
If not, when the CONST_A be recalculated? And would the next structure fix it?
module CALCULATE_CONST_A
import json
CONST_A = json.load(open(...))
module A
from CALCULATE_CONST_A import CONST_A
further imports of A...
Final question: What are the best practices for creating precalculated constants?
Well, let's experiment:
tbi.py
print("Hello, World!")
file1.py
import tbi
print("This is file1")
file2.py
import file1
import tbi
print("This is file2")
And now, when we run file2, we see:
$ python file2.py
Hello, World!
This is file1
This is file2
So the answer to your question is yes, python modules are executed once only. If tbi.py were executed twice, we would have seen "Hello World" printed twice. It's logical, then, to conclude that the attributes of the file are set the first time that file is imported.
Furthermore, more experimentation can show you that, if I put a global variable in tbi, and both file1 and file2 modified it, they would both be modifying the same object. This is visible in a number of built-in packages: for example, changing the value of sys.stdout (the file descriptor for standard output, and a global variable specified when the sys module is first loaded) changes it for the entire program, not just the file that modified it.
If you're worried about this sort of thing causing errors, the best thing to do is to not use global variables - instead, use classes and assign them default values when constructed.

python importing a function in which I define a global variable [duplicate]

This question already has an answer here:
Get variable from another file - python
(1 answer)
Closed 4 years ago.
I'm having difficulty accessing a variable.
I'm working toward the following, calling python script from bash, with arguments, which then imports a function defined in a second python script, executes it and thereby creates a variable which will be used later in the first python script.
At the moment,to test I'm copying and pasting directly into a Python terminal some commands like this:
from script2 import *
foofunction(arg)
print(newlist)
The foo function defined in script2 is executing, I can see files have been written but when I try to print the list supposedly created while executing the imported function, I get a message telling me it's undefined.
Inside my script2.py, i made sure to enter a statement
global newlist
before defining its length and populating it.
I'm scratching my head at this stage.
You should refer to newlist and the module where it is defined like this:
from script2 import *
foofunction(arg)
print(script2.newlist)

How can I execute __main__ from another Python module? [duplicate]

This question already has answers here:
Calling if __name__ == '__main__': in one module from a function in another module [closed]
(2 answers)
Closed 6 years ago.
I have a python file that I am not the maintainer of that looks like the code below. Without modifying the code to put everything under the if __name__, is there a way to import this from another module so I can execute it and pass arguments programmatically?
import configargparse
if __name__ == '__main__':
args = get_args()
#more code to execute...
You can't, for the most part. That code isn't exposed in a useful fashion. If you are able to modify the source file, the typical solution would be to move all of that code out of the if __name__ == '__main__' block and put it into a main() function instead.
It's possible to use the execfile function to sort of do what you want, as described here, but this is an ugly solution for a number of reasons (the import statement is being used only for side effects, because you're cheating and using it to get the filename, and module level variables will probably not behave as you expect when referenced as module.var, as described in some of the comments on that page).
And even in this example, it's not clear that there's a useful way to pass arguments. I guess you could set sys.argv explicitly, but look how hacky this is already smelling...

How do I find out the file that is the beginning of a Python program? [duplicate]

This question already has answers here:
Find path to currently running file
(8 answers)
Closed 7 years ago.
Let's assume that I have a program that consists of at least two files, magic.py which is part of the herebemagic module...
def foo():
# This line is what my question will be all about
pass
...and main.py, which starts the program:
import os
from herebemagic import magic
print("This is where this file lies: %s" % (repr(os.path.abspath(__file__)), ))
magic.foo()
As demonstrated, finding a module's file, and the path that it is in, is trivial. But how would I, in magic.py, get a reference to main.py's module (being the one that was invoked by the interpreter, not necessarily the one that imported herebemagic directly), so that I can get at its file?
Of course I could just figure it out in main.py, and pass it down to foo(), but in practice there can be an arbitrary number of modules in between the two, and in my case, it'd be ugly to pass it down (I'm loading a lot of modules with importlib, and the information is currently only relevant to one of the modules). Or I could use a builtin, but that is a namespace that no one wants to litter.
The Python executable is called with the name of the main script as command line argument. Python keeps this in sys.argv:
sys.argv[0]

Categories

Resources