[英]Can you make a python script behave differently when imported than when run directly?
I often have to write data parsing scripts, and I'd like to be able to run them in two different ways: as a module and as a standalone script.我经常需要编写数据解析脚本,并且我希望能够以两种不同的方式运行它们:作为模块和作为独立脚本。 So, for example:所以,例如:
def parseData(filename):
# data parsing code here
return data
def HypotheticalCommandLineOnlyHappyMagicFunction():
print json.dumps(parseData(sys.argv[1]), indent=4)
the idea here being that in another python script I can call import dataparser
and have access to dataParser.parseData
in my script, or on the command line I can just run python dataparser.py
and it would run my HypotheticalCommandLineOnlyHappyMagicFunction
and shunt the data as json to stdout.这里的想法是,在另一个 python 脚本中,我可以调用import dataparser
并在我的脚本中访问dataParser.parseData
,或者在命令行上,我可以运行python dataparser.py
,它将运行我的HypotheticalCommandLineOnlyHappyMagicFunction
并将数据分流为 json到标准输出。 Is there a way to do this in python? python有没有办法做到这一点?
The standard way to do this is to guard the code that should be only run when the script is called stand-alone by执行此操作的标准方法是保护仅当脚本被独立调用时才运行的代码
if __name__ == "__main__":
# Your main script code
The code after this if
won't be run if the module is imported.如果导入了模块,此if
之后的代码将不会运行。
The __name__
special variable contains the name of the current module as a string. __name__
特殊变量包含当前模块的名称作为字符串。 If your file is called glonk.py
, then __name__
will be "glonk"
if the the file is imported as a module and it will be "__main__"
if the file is run as a stand-alone script.如果您的文件名为glonk.py
,那么如果文件作为模块导入,则__name__
将为"glonk"
,如果文件作为独立脚本运行,则为"__main__"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.