sys.argv[] 用法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_39377418/article/details/99625568

运行环境 : Python 3.6.0

sys.argv[]是用来获取命令行输入的参数的(参数和参数之间空格区分) , sys.argv[0]表示代码本身文件路径,所以从参数1开始,表示获取的参数了

sys.argv,其实就是一个list,它是sys模块下的一个全局变量,第一个元素是模块名、后面是依次传入的参数,比如可以这样传入 pyton test.py a b c d,一共传入a、b、c、d四个参数

示例 1 :

  test.py :

# -*-coding: utf-8 -*-
# @Module: test.py
from sys import argv

script, first, second, third = argv

print("The script is called:{%s}" % script)
print("Your first variable is:{%s}" % first)
print("Your second variable is:{%s}" % second)
print("Your third variable is:{%s}" % third)

# 运行 , 打开cmd运行这个文件

运行结果 : 

示例 2 :

  test.py :

# -*-coding: utf-8 -*-
# @Module: test.py

import os
os.system(sys.argv[1])

  os.system 是打开程序的命令, 把这个代码保存为一个脚本文件, test.py在命令行中运行 test.py notepad就可以打开记事本了

示例 3 :

扫描二维码关注公众号,回复: 7203064 查看本文章
# -*-coding: utf-8 -*-
# @Module: test.py

import sys


def readFile(file_name):  # 从文件中读出文件内容
    """ Print a file to the standard output. """
    with open(file_name, 'r', encoding='utf-8') as f:
        lines = f.read()
        print(lines)  # notice comma  分别输出每行内容


if __name__ == '__main__':
    # Script starts from here
    if len(sys.argv) < 2:
        print('No action specified.')
        sys.exit()
    elif 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('''\
            This program prints files to the standard output.
            Any number of files can be specified.
            Options include:
                --version : Prints the version number
                --help    : Display this help''')
        else:
            print('Unknown option.')
        sys.exit()
    else:
        for file_name in sys.argv[1:]:  # 当参数为文件名时,传入readfile,读出其内容
            readFile(file_name)

1.  命令行带参数运行:python test.py --version

2. 命令行带参数运行:python  test.py --help 

 3. 在 test.py 目录下,新建 test.txt 的记事本文件 , 控制台中输入多个参数用空格区分。

  test.txt :

身边有人来有人走。有人去去就回。有人头也不回。
我会释怀。
我知道,有人走了,就会再有来人替代他。
多年后,或许我还会记得,有人在我的世界里出现过。
或许潮起潮落,或许波澜未起。

  控制台 : python  test.py test.txt 

猜你喜欢

转载自blog.csdn.net/qq_39377418/article/details/99625568