Python-sys.argv——notes

Python sys.argv

Test1

sys.argv-test.py文件,加入代码如下:

import sys

def print_sys_argv():
    print(sys.argv[0])

shell运行如下:

python3 sys.argv-test.py

Output:

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py
sys.args-test.py

Test2

sys.argv-test.py文件,加入代码如下:

import sys

def print_sys_argv():
    print(sys.argv[0])
    print(sys.argv[1])

shell运行如下:

python3 sys.argv-test.py 123

Output:

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py
sys.args-test.py
123

Test3

sys.argv-test.py文件,加入代码如下:

import sys

def print_sys_argv():
    print(sys.argv[2:])

shell运行如下:

python3 sys.argv-test.py a b c d e f g

Output:

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py a b c d e f g
['b', 'c', 'd', 'e', 'f', 'g']

sys.argv[0]是脚本名称,sys.argv[1:]是后面跟如的参数列表。

Test4

import sys


def print_args():
    if len(sys.argv) < 2:
        sys.exit()
    else:
        op = sys.argv[1][2:]
        if op == 'help':
            print('Are you asking for help?')
        elif op == 'print':
            print('Do you want print something?')
        elif op == 'play':
            print('Do you want to play with somebody?')
        else:
            print('There is no such option '+ op)

if __name__ == '__main__':
    print_args()

Output:

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py --help
Are you asking for help?

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py --print
Do you want print something?

D:\Python\Python3DocumentOfficial>python3 sys.args-test.py --play
Do you want to play with somebody?
D:\Python\Python3DocumentOfficial>python3 sys.args-test.py --love
There is no such option love

你可能感兴趣的:(Python-sys.argv——notes)