简体   繁体   中英

Running several Python scripts with from one function

I have a few .py programs I run in my IDE separately (I guess they just run as separate processes, right). Each of them has a couple of classes, some global variables etc and the main function. How can I achieve the same effect programmatically, ie run these scripts in particular order?

I've tried several methods, but they didn't seem to give the same effect as starting those scripts 'by hand'.

您是否尝试编写其他脚本,以从这些单独的程序中导入所需的内容并以您指定的方式运行它们?

您可以制作第三个脚本,其中包含您要运行的所有其他脚本的名称,然后给python一个subprocess命令调用在此处了解有关子进程的更多信息

Generally speaking, importing a script will run the script. If I have some script called spam.py that reads:

print 'eggs'

Then I can write another script run.py in the same directory with the following:

import spam

When I run a python run.py , it will output 'eggs'.

Most scripts that are used as library modules that you import just contain function and class definitions. These modules are still run when you import them, but they don't actually do anything other than to make the definitions.

So if I change spam.py to read:

def main():
    print 'eggs'

Then when I run python run.py nothing will actually happen. But I can change run.py to read as follows:

import spam
spam.main()

Now it will define main in the namespace spam , and by calling main() I print 'eggs'.

Finally, sometimes scripts are meant to be both used as modules to be imported and scripts to be run on their own. For this it is often the case that when imported you don't want the script to do anything besides define modules and classes. You can make spam.py work this way as follows:

def main():
    print 'eggs'

if __name__ == '__main__':
    main()

Now if you run python spam.py it will print 'eggs' to the screen. But if you import spam it will not. The suite of statements inside if __name__ == '__main__': is only run if you call the script directly.

However, you can still get the same behavior from spam as doing python spam.py by importing spam and calling main :

import spam
spam.main()

Again, this prints eggs to the screen.

So if you have a number of scripts foo.py , bar.py , baz.py that you want to run in sequence from another script, you just import all of the scripts and then if any commands are protected by if __name__ == '__main__': , you run them in your calling script making sure to prepend the appropriate namespace to each command (ie if main() is called in foo.py , then you call foo.main() ).

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