python標準庫之sys模組 學習

來源:互聯網
上載者:User

標籤: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模組 學習

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.