zoukankan      html  css  js  c++  java
  • python标准库之sys模块 学习

    通过这节学习来知道如何在linux下执行python代码

    sys是system的缩写,用来获取操作系统和编译器的一些配置,设置及操作

    我们要充分的理解他最好是在linux的环境下进行测试

    sys.argv[0] ,返回的是代码所在文件的路径

    [mark@bogon ~]$ vi test.py
    [mark@bogon ~]$ python3 test.py
    test.py
    [mark@bogon ~]$ cat test.py
    import sys
    print(sys.argv[0])

    sys.argv[1],   返回的是代码后的第一个参数 ,以此类推

    [mark@bogon ~]$ vi test.py
    [mark@bogon ~]$ python3 test.py 1 2 3 4
    test.py 1
    [mark@bogon ~]$ cat test.py
    import sys
    print(sys.argv[1])

    通过两个代码也就清晰的看出来了argv的用处与用法

    下面的代码可以体现出sys.argv的应用

    import sys
    def 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的运行环境下才可以看出效果

    [mark@bogon ~]$ python3 test.py --version
    ['test.py', '--version']
    test.py
    Version 1.2
    [mark@bogon ~]$ python3 test.py --help
    ['test.py', '--help']
    test.py
  • 相关阅读:
    ArcGIS Engine 常用方法(转)
    正则表达式 C#System.Text.RegularExpressions.Regex
    ae中栅格数据转为矢量数据 (转)
    ArcEngine 渲染的使用 (转)
    C#字符串分割成数组,中间多空格
    <C++ GUI Programming with Qt4 ,Second Edition> 学习笔记
    perl module and its package
    static_cast reinterpret_cast
    阅读<inside the c++ object modle > 有感
    C++ virtual table
  • 原文地址:https://www.cnblogs.com/shidi/p/7473091.html
Copyright © 2011-2022 走看看