Python - run external script

非 Y 不嫁゛ 提交于 2019-12-08 04:42:51

问题


Does someone know if I have a script one.py which is written the following way:

if __name__ == '__main__':
    # Do something

And I want to call that main function from another script. How should I do that?

I guess it would be something like (let's say this is launcher.py)

# 'one' stands for import from `one.py` module
import one

if __name__ == '__main__':
    one.main()

The only problem is that I can't call main() this way.

How should this be done?


回答1:


with file('a.py','rU') as f:
  co=compile(f.read(),'foobar','exec')
  exec co in {'__name__':'__main__'}



回答2:


Define your script like:

def main():
    # Do something

if __name__ == '__main__':
    # Processing of possible input parameters here and passing to main
    main()

Then you can do

# 'one' stands for import from `one.py` module
import one

if __name__ == '__main__':
    one.main()

Of course you can name the function however you want.



来源:https://stackoverflow.com/questions/4463639/python-run-external-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!