Powershell 相当于 python 的 if __name__ == '__main__': [英] Powershell equivalent of python's if __name__ == '__main__':

查看:61
本文介绍了Powershell 相当于 python 的 if __name__ == '__main__':的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很喜欢 python 做这样的事情的能力:

I am really fond of python's capability to do things like this:

if __name__ == '__main__':
    #setup testing code here
    #or setup a call a function with parameters and human format the output
    #etc...

这很好,因为我可以将 Python 脚本文件视为可以从命令行调用的东西,但我仍然可以轻松地将其函数和类导入到单独的 Python 脚本文件中,而不会触发默认的运行自命令行行为".

This is nice because I can treat a Python script file as something that can be called from the command line but it remains available for me to import its functions and classes into a separate python script file easily without triggering the default "run from the command line behavior".

Powershell 是否有类似的工具可供我利用?如果不是,我应该如何组织我的函数文件库,以便我在开发它们时可以轻松地执行其中的一些?

Does Powershell have a similar facility that I could exploit? And if it doesn't how should I be organizing my library of function files so that i can easily execute some of them while I am developing them?

推荐答案

$MyInvocation 有很多关于当前上下文和调用者的信息.也许这可用于检测脚本是点源(即导入)还是作为脚本执行.

$MyInvocation has lots of information about the current context, and those of callers. Maybe this could be used to detect if a script is being dot-sourced (i.e. imported) or executed as a script.

脚本可以像函数一样运行:使用 param 作为文件中第一个非公共/空白来定义参数.目前尚不清楚(需要尝试不同的组合)如果您点源一个以 param...

A script can act like a function: use param as first non-common/whitespace in the file to defined parameters. It is not clear (one would need to try different combinations) what happens if you dot-source a script that starts param...

模块可以直接执行代码,也可以导出函数、变量……并且可以带参数.也许模块中的 $MyInvocation 可以检测到这两种情况.

Modules can directly execute code as well as export functions, variables, ... and can take parameters. Maybe $MyInvocation in a module would allow the two cases to be detected.

附加:

$MyInvocation.Line 包含用于执行当前脚本或函数的命令行.它的 Line 属性具有用于执行的脚本文本,当点源时,它将以."开头,但如果作为脚本运行则不会(显然是使用的情况)正则表达式匹配以允许在句点周围使用可变空格).

$MyInvocation.Line contains the command line used to execute the current script or function. Its Line property has the scrip text used for the execution, when dot-sourcing this will start with "." but not if run as a script (obviously a case to use a regex match to allow for variable whitespace around the period).

在脚本中作为函数运行

这篇关于Powershell 相当于 python 的 if __name__ == '__main__':的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆