Get the App
SLTechnology News&Howtos  ›  Servers  › 

How to use the sys.argv [] method in python

Shulou Source: shulou.com Published: 2022-06-01 18:36:15 09月20日 Update

It is believed that many inexperienced people have no idea about how to use the sys.argv [] method in python. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Sys.argv [] is used to get command-line arguments, and sys.argv [0] represents the file path of the code itself, so start with the second, sys.argv [1].

Note: parameters are separated by spaces

Create a file called sysargv.py with the following contents:

Import sys

Print ('the first argv:', sys.argv [0],'\ n') # shows the first parameter

Print ('the second argv:', sys.argv [1],'\ n') # shows the second parameter

Print ('the third argv:', sys.argv [2],'\ n') # shows the third parameter, and so on

The results of the execution are as follows:.

E:\ lib > learnsysargv.py yang.txt yangqilong

The first argv: e:\ lib\ learnsysargv.py-- the path to the pyython file

The second argv: yang.txt-- Parameter 1

The third argv: yangqilong-- Parameter 2

I revised an example in the official textbook.

Import sys

Print ('the first argv:', sys.argv [0])

Print ('the second argv:', sys.argv [1])

# print ('the third argv:', sys.argv [2])

If len (sys.argv)

< 2: print ('No action specified.') sys.exit() 解释一下下面IF语句的语法:判断参数1是否是以'--'开头 if sys.argv[1].startswith('--'): ption = sys.argv[1][2:]//把参数1从第三个字符开始的字符串赋值给 option(去掉'--'字符),直到参数1后面的空格。 # fetch sys.argv[1] but without the first two characters if ption == 'v': print ('Version 1.2') elif option == 'h': print ('This program prints files to the standard output.\nAny number of files can be specified.\n\ Options include:\n\ --v : Prints the version number\n\ --h : Display this help') 程序输出结果: E:\lib>

Sysargv.py-- h

The first argv: e:\ lib\ sysargv.py

The second argv:-h

This program prints files to the standard output.

Any number of files can be specified.

Options include:

-v: Prints the version number

-h: Display this help

E:\ lib > sysargv.py-- v

The first argv: e:\ lib\ sysargv.py

The second argv:-- v

Version 1.2

After reading the above, have you mastered how to use the sys.argv [] method in python? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Parameters methods content characters files three more spaces results paths problems helpless and so on code examples reasons commands strings official Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia OPPO Reno vpn MariaDB macOS