我有一个Python脚本,它通过打印返回数据,不使用函数。
我现在想要以相同的方式从脚本中创建一个函数,但不应该打印数据,它应该由app函数返回。
当然我可以手动编写" def myapp():",制作所有缩进,并在脚本的最后一行调用它,但我想知道是否有工具那个?
答案 0 :(得分:1)
始终将您的脚本编写为一个或多个以两个“魔术”行结尾的函数。合适的模板是
import sys # if you want a system return code
MY_CONSTANT = "whatever" # a symbolic constant
def a_function( args): # replace with your useful stuff
pass
# def b_function( args): # as many more defs as are useful
# can refer to / use both a_function (above) and c_function (below)
# def c_function()
# etc
def main():
print( "Script starting ...")
# parse arguments, if any parsing needed
# do stuff using the functions defined above
# print output, if needed
print( "End of script")
sys.exit(0) # 0 is Linux success, or other value for $? on exit
# "magic" that executes script_main only if invoked as a script
if __name__ == "__main__": # are we being invoked directly from command line?
main() # if so, run this file as a script.
为什么呢?此文件(myfile.py
)也可用作导入,解释器提示符或其他文件/脚本/模块。它将定义常量和函数,但在导入时实际上不会运行任何东西。任
import myfile
所以你可以参考myfile.a_function
,myfile.MY_CONSTANT
等。
或
from myfile import a_function
然后您可以在不需要前缀的情况下调用a_function(args)
。您经常会看到test
或一些随机名称:main()
并不特殊。