微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在python中使用sys.argv来检查参数的长度,以便它可以作为脚本运行?

好的,这是我的代码的一部分(我已导入sys)

if __name__ == '__main__':


MyCaesarCipher = CaesarCipher() #MyCaesarCipher IS a CaesarCipher()

if len(sys.argv) >1:
    #what will it check? 

Done = False   
while not Done:
    print('C Clear All')
    print('L Load Encrypted File')
    print('R Read Decrypted File')
    print('S Store Encrypted File')
    print('W Write Decrypted File')
    print('O Output Encrypted Text')
    print('P Print Decrypted Text')
    print('E Encrypt Decrypted Text')
    print('D Decrypted Encrypted Text')
    print('Q Quit')
    print('----------------')
    print('Enter Choice>')

所以我想做的是如果命令行长度大于1,程序将作为脚本运行.

这是指令:

If no command line arguments are input,then the script enters menu
mode. If more than 1 command line argument (anything other than script
name) is provided during the run of the script it enters single run
mode.

不过,我不知道这意味着什么.

解决方法

什么是sys.arvg:

传递给Python脚本的命令行参数列表. argv [0]是脚本名称.

演示:
文件名:1.py

import sys

if __name__=="__main__":
    print "command arguments:",sys.argv

输出

$python 1.py arg1 arg2 
command arguments: ['1.py','arg1','arg2']
$python 1.py
command arguments: ['1.py']

你的问题是,我们必须通过Command Line Argument和Menu运行代码.

用户从命令行提供Enter Choice时,请将提供的值用于下一个进程.

如果用户未从命令行提供“输入选择”,则要求用户菜单中输入“选择”.

演示:

文件名:1.py

import sys

if __name__ == '__main__':
    try:
        arg_command = sys.argv[1]
    except IndexError:
        arg_command = ""

    Done = False
    while not Done:
        if arg_command=="":
            print('\nMenu')
            print('C Clear All')
            print('L Load Encrypted File')
            print('Q Quit')
            print('----------------')
            print('Enter Choice>')
            command = raw_input('Enter Selection> ').strip()[0].upper()
        else:
            command = arg_command
            #- set arg value to empty to run Menu option again.
            arg_command = ""

        if command == 'C':
            print "In Clear All event."
        elif command == 'L':
            print "In Clear All event."
        elif command == "Q":
            break
        else:
            print "Wrong Selection."

输出

输入命令行给出的选择:

$python 1.py C
In Clear All event.

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$

没有命令行参数.

$python 1.py

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> l
In Clear All event.

Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐