Learn how to execute Python code under Linux in this section.
SYS is the abbreviation of system, which is used to obtain some configuration, setup and operation of the operating system and compiler.
We have to fully understand that he had better be tested in a Linux environment.
Sys.argv[0], returns the path to the file where the code is located
[Email protected] ~~ ~]$ Cat test.py Import SYS Print (Sys.argv[0])
SYS.ARGV[1], returns the first parameter after the code, and so on
[Email protected] ~ ~]$ Python3 test.py 1 2 3 41~]$ cat test.pyimport sy sprint(sys.argv[1])
The use and usage of argv are clearly seen through the two code.
The following code can show the application of SYS.ARGV
ImportSYSdefReadFile (filename): F=open (filename) whileTrue:line=F.readline ()ifLen (line) = =0: Break Print(line) f.close ()Print(SYS.ARGV)Print(sys.argv[0])ifLen (SYS.ARGV) <2: Print("NO Action specified") Sys.exit ()ifSys.argv[1].startswith ("--"): Option=sys.argv[1][2:] #fetch sys.argv[1] But without the first and the characters ifoption=="version":#when the command line argument is--version, the version number is displayed Print("Version 1.2") elifoption==" Help":#when the command line argument is--help, the Help content is displayed Print("") Else: Print("Unknown Option") Sys.exit ()Else: forFileNameinchSys.argv[1:]:#When the argument is a file name, pass in the Readfine and read its contentsReadFile (filename)
Note that it is best to run the Linux environment before you can see the effect
[Email protected] ~]$ Python3 test.py--version['test.py'-- Version'1.2~]$ python3 test.py--help['test.py ' ' --help ' ]test.py
The SYS module learning of the Python standard library