Run python file inside another - python

I am using python 3.5
I want to run a python script calling from another python script.
In particular, say I have script A (in particular, this is the exact file that I want to run: script A file):
Script A is the following.
if __name__ == '__main__':
args = argparser.parse_args()
_main(args)
I am running script B, inside script B, it calls script A.
How do I simply do this by calling the main function of script A while running script B?
Please no os.system('python scriptA.py 1'), this is not what i want. thanks

normally you can import it and call the main function
like
import script_a
...
script_a._main()
of course it could be that the script_a is not in you src structure, so that you can not simple import, or script_a is completely somewhere else.
Suppose the path of the script_a is path_a
you can
import sys
sys.path.append(path_a)
import script_a
script_a._main()
if you want to pass the args to script_a , in your script_b
import script_a
...
if __name__ == '__main__':
args = argparser.parse_args()
script_a._main(args)

In Script B simply import Script A,
import script_A
or
from script_A import *
now you can access your script A in script B

Treat the file like a module and put import scriptA at the top of your file.
You can then use scriptA.main(1) where 1 is the argument you are passing to it.
N.B When importing do not put .py at the end.

If you have code which is not indented inside of script A and if you import script A inside script B, it will automatically first run script A and then move on to the __main__() of script B. How ever if you wish control when the execution of script A begins, then , indent your code in Script A or code it in a normal function such as def start() .
Now, import Script A into Script B as follows
import ScriptA
And run the script A as
ScriptA.start()
NOTE: Make sure that script A and script B are in the same directory for this to work. Hope this solves your purpose. Cheers!

Related

How to execute another Python file from current script?

So I have a login script called login.py. When user log in, script will create a user session and execute main.py and close login.py. How to do this?
I'm a little confused by what you need help with but try this:
from fileName import function_you_want
Ideally you don't want a script to run on an import. It can cause some unexpected things to happen. At the bottom of main.py I would use this:
if __name__ == "__main__":
call_your_function()
This way you can do tests by running the script directly or calling a specific method from another py file without running the script.
What you can do is import that file main.py like import main. If you want everything from that file, from main import *
Then, after the user logins, destroy your main window using <Tk>.destroy() and then call your function.

Running python program with arguments from another program

I want to call a python program from current program,
def multiply(a):
return a*5
mul = sys.argv[1]
I saved this file as test.py.so from the current file I'm calling it but i want to run the code in parallel like multiprocessing queue,But its not working.
what I tried so far,
import os
import sys
import numpy as np
cwd = os.getcwd()
l = [20,5,12,24]
for i in np.arange(len(l)):
os.system('python test.py multiply[i]')
I want to run the main script for all list items parallelly like multiprocessing. How to achieve that?
If you want to make your program work like that using that the os.system, you need to change the test.py file a bit:
import sys
def multiply(a):
return a*5
n = int(sys.argv[1])
print(multiply(n))
This code written like this takes the second element (the first one is just the name of the file) of argv that it took when you executed it with os.system and converted it to an integer, then executed your function (multiply by 5).
In these cases though, it's way better to just import this file as a module in your project.

Importing variables from another Python script

Is it possible to import a Python script into a main script and then just use the variables? I don't want the other script to execute inside of the main script, just attach one of the variables...
If you can edit the script being imported, there's a solution:
Put all the executed code into a block starting with
if __name__ == '__main__':
In this way, the code in the if block above will be executed only if the script is run directly. i.e. when you run python script.py.
You can import only the variable like this:
from script import var
If you want to import the variable without going through the whole script, then as per Python's design it's not possible. import will always go through the whole script being imported, and will avoid whatever that's inside __name__ == '__main__'.
You have an option to read the script file and find the variables, then do it yourself by parsing and executing it, but IMO that's unnecessary job to do since you have import.
You can see the answers under Python: import module without executing script

How to include py file based on the command line input?

My python script has to include other python scripts in the code. And I want the other scripts to be passed as command line arguments.
For example:
My script is test.py, and I want to include first.py in my code based on the command line input.
Command line input
python test.py first.py
In the code I want first.py to be imported as in:
import first
But I can't figure out a way. I tried using optparse and fileInput, but they didn't turn out to be what I had intended.
I don't think it is best practice to import module from arguments, but if you really want to do that, could try below code:
import sys
for file_name in sys.argv[1:]:
module_name = file_name.replace('.py', '')
exec('import %s' % module_name)
I don't know the best way to answer your question. But here is my solution. Again, this may not be the best solution-
module_name = input()
with open('file_name.py', 'w') as py_file:
py_file.write('import ' + module_name)
Why doesn't a simple import statement in the original code do the job? Like so:
import first
#
# The rest of the program.
#
Then from the command line, you only need to run
python test.py
As long as test.py and first.py are in the same directory, this approach is effectively "including" first.py in test.py. Please include more information about why you want to pass first.py as a command line argument. It seems to me, since you already know what your program will be doing with first.py, and you have to write your code under the assumption that first.py will be imported anyway, you might as well just do it at the beginning of test.py.
python test.py first.py - In this case, test.py is argv[0] and first.py is argv[1]
Add below code in your test.py
from sys import argv
execfile(argv[1])

Main program variables in side programs (Python)

How do I use variables that exist in the main program in the side program? For example, if I were to have Var1 in the main program, how would I use it in the side program, how would I for example, print it?
Here's what I have right now:
#Main program
Var1 = 1
#Side program
from folder import mainprogram
print(mainprogram.Var1)
This I think would work, if it didn't run the main program when it imports it, because I have other functions being executed in it. How would I import all the main program data, but not have it execute?
The only thing I thought of was to import that specific variable from the program, but I don't know how to do it. What I have in my head is:
from folder import mainprogram
from mainprogram import Var1
But it still excecutes mainprogram.
Your approach is basically correct (except for from folder import mainprogram - that looks a bit strange, unless you want to import a function named mainprogram from a Python script named folder.py). You have also noticed that an imported module is executed on import. This is usually what you want.
But if there are parts of the module that you only want executed when it's run directy (as in python.exe mainprogram.py) but not when doing import mainprogram, then wrap those parts of the program in an if block like this:
if __name__ == "__main__":
# this code will not be run on import

Categories