2024-04-26 04:47:16 发布
网友
我有这个密码:
def hello(): return 'Hi :)'
如何直接从命令行运行此命令?
只要把hello()放在函数下面的某个地方,它就会在您这样做时执行python your_file.py
hello()
python your_file.py
对于更整洁的解决方案,您可以使用:
if __name__ == '__main__': hello()
这样,只有在运行文件时才会执行该函数,而不是在导入文件时执行。
使用-c(命令)参数(假设文件名为foo.py):
-c
foo.py
$ python -c 'import foo; print foo.hello()'
或者,如果您不关心命名空间污染:
$ python -c 'from foo import *; print hello()'
中间立场:
$ python -c 'from foo import hello; print hello()'
python -c 'from myfile import hello; hello()',其中myfile必须替换为Python脚本的基名。(例如,myfile.py变成myfile)。
python -c 'from myfile import hello; hello()'
myfile
myfile.py
但是,如果hello()是Python脚本中的“永久”主入口点,则通常的方法如下:
def hello(): print "Hi :)" if __name__ == "__main__": hello()
这允许您通过运行python myfile.py或python -m myfile来执行脚本。
python myfile.py
python -m myfile
这里有一些解释:__name__是一个特殊的Python变量,它保存当前正在执行的模块的名称,除了从命令行启动模块时的,在这种情况下,它变成"__main__"。
__name__
"__main__"
只要把
hello()
放在函数下面的某个地方,它就会在您这样做时执行python your_file.py
对于更整洁的解决方案,您可以使用:
这样,只有在运行文件时才会执行该函数,而不是在导入文件时执行。
使用
-c
(命令)参数(假设文件名为foo.py
):或者,如果您不关心命名空间污染:
中间立场:
python -c 'from myfile import hello; hello()'
,其中myfile
必须替换为Python脚本的基名。(例如,myfile.py
变成myfile
)。但是,如果
hello()
是Python脚本中的“永久”主入口点,则通常的方法如下:这允许您通过运行
python myfile.py
或python -m myfile
来执行脚本。这里有一些解释:
__name__
是一个特殊的Python变量,它保存当前正在执行的模块的名称,除了从命令行启动模块时的,在这种情况下,它变成"__main__"
。相关问题 更多 >
编程相关推荐