简体   繁体   English

命令行参数PYTHON

[英]command line arguments PYTHON

Code

import sys

def main()
    print(sys.argv)

Version - 3.3 版本-3.3

File name Pytest.py 文件名Pytest.py

running the file with syntax pytest.py aaa bbb ccc 使用语法pytest.py aaa bbb ccc运行文件

But it didn't print anything and not giving any error also 但是它没有打印任何东西,也没有给出任何错误

You never call main() . 您永远不会调用main()

Python has no special main function that is run automatically, so instead, you can place the code that you want to run when the file is called from the command line into a special if block: Python没有自动运行的特殊main函数,因此,可以将从命令行调用文件时要运行的代码放入特殊的if块中:

import sys

def main():
    print(sys.argv)

if __name__ == '__main__':
    main()

To elaborate @Blender's answer: Python functions does not compile like in C. Functions are statements - they are being executed when the control encounters them, and it begins at the first line of the file. 要详细说明@Blender的答案:Python函数不会像C中那样进行编译。函数是语句 -当控件遇到它们时便正在执行它们,并且它始于文件的第一行。

The following code is perfectly legal: 以下代码完全合法:

# get b somehow
if b:
    def foo(): return 1
else:
    def foo(): return 2

print(foo())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM