標籤:pen 命令 配置 代碼 ecif har pre option specified
通過這節學習來知道如何在linux下執行python代碼
sys是system的縮寫,用來擷取作業系統和編譯器的一些配置,設定及操作
我們要充分的理解他最好是在linux的環境下進行測試
sys.argv[0] ,返回的是代碼所在檔案的路徑
[[email protected] ~]$ vi test.py[[email protected] ~]$ python3 test.pytest.py[[email protected] ~]$ cat test.pyimport sysprint(sys.argv[0])
sys.argv[1], 返回的是代碼後的第一個參數 ,以此類推
[[email protected] ~]$ vi test.py[[email protected] ~]$ python3 test.py 1 2 3 4test.py 1[[email protected] ~]$ cat test.pyimport sysprint(sys.argv[1])
通過兩個代碼也就清晰的看出來了argv的用處與用法
下面的代碼可以體現出sys.argv的應用
import sysdef readfile(filename): f=open(filename) while True: line=f.readline() if len(line)==0: break print(line) f.close()print(sys.argv)print(sys.argv[0])if len(sys.argv)<2: print(" no action specified") sys.exit()if sys.argv[1].startswith("--"): option=sys.argv[1][2:] #fetch sys.argv[1] but without the first two characters if option=="version": #當命令列參數為--version,顯示版本號碼 print("Version 1.2") elif option=="help":#當命令列參數為--help,顯示協助內容 print("") else: print("Unknown option") sys.exit()else: for filename in sys.argv[1:]:#當參數為檔案名稱時,傳入readfine,讀出其內容 readfile(filename)
注意最好都要在linux的運行環境下才可以看出效果
[[email protected] ~]$ python3 test.py --version[‘test.py‘, ‘--version‘]test.pyVersion 1.2[[email protected] ~]$ python3 test.py --help[‘test.py‘, ‘--help‘]test.py
python標準庫之sys模組 學習