简体   繁体   English

您能否使 python 脚本在导入时和直接运行时表现不同?

[英]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.

相关问题 为什么我的python类方法本身的行为与我运行模块时的行为不同? - Why does my python class method behave differently by itself than when I run the module? 第二次按下时使按钮的行为有所不同(Python) - Make a button behave differently when pressed a second time (Python) 在导入的__init__.py中,导入的行为会有所不同 - Imports behave differently when in __init__.py that is imported 如何在导入时不运行Python Decorator - How to make Python Decorator NOT run when imported 计划的 cron Python 脚本日志记录的工作方式与手动运行时不同 - Scheduled cron Python script logging working differently than it does when run manually Python代码的行为与在终端中运行时的行为不同 - Python code acting differently than when run in terminal 我可以让我的自定义 pytorch 模块在调用 train() 或 eval() 时表现不同吗? - Can I make my custom pytorch modules behave differently when train() or eval() are called? 为什么在Python中将迭代器设置为变量与直接在列表推导中使用迭代器的行为有所不同? - Why does setting an iterator to a variable in Python behave differently than using it directly in a list comprehension? 当你在其他应用程序上时运行python脚本 - run python script when you are on other applications 为什么RestrictedPython在与Python 3.6一起使用时表现不同? - Why does RestrictedPython behave differently when used with Python 3.6?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM