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?
with file('a.py','rU') as f:
co=compile(f.read(),'foobar','exec')
exec co in {'__name__':'__main__'}
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