Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
793 views
in Technique[技术] by (71.8m points)

how do I determine whether a python script is imported as module or run as script?

The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python?

The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the module is only imported to use it in another script. (I want to be able to use one script as both library and program.) I am afraid the vanilla way would be to build the lib and a second script that uses it, but I'd like to have a second option for small tool/libs.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

from python docs:

When you run a Python module with

python fibo.py

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:

if __name__ == '__main__':
    # Running as a script

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...