简体   繁体   中英

Run python file inside another

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.

NB 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM