如何在 python 中使用 sys.argv 检查参数的长度,以便它可以作为脚本运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29045768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use sys.argv in python to check length of arguments so it can run as script?
提问by Elsa
Ok so here is part of my code (I have imported 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>')
So the thing is I want to do is if the command line length is more than 1, the program runs as a script.
所以我想做的是,如果命令行长度大于 1,则程序作为脚本运行。
This is the instruction:
这是指令:
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.
如果没有输入命令行参数,则脚本进入菜单模式。如果在脚本运行期间提供了 1 个以上的命令行参数(脚本名称以外的任何内容),它将进入单次运行模式。
I do not know what this means, though.
不过,我不知道这意味着什么。
采纳答案by Vivek Sable
What is sys.arvg:
什么是 sys.arvg:
The list of command line arguments passed to a Python script. argv[0]is the script name.
传递给 Python 脚本的命令行参数列表。argv[0]是脚本名称。
Demo: File Name: 1.py
演示:文件名:1.py
import sys
if __name__=="__main__":
print "command arguments:", sys.argv
Output:
输出:
$ python 1.py arg1 arg2
command arguments: ['1.py', 'arg1', 'arg2']
$ python 1.py
command arguments: ['1.py']
Your problem is, we have to run code by Command Line Argument and by Menu also.
您的问题是,我们还必须通过命令行参数和菜单运行代码。
When User provided the Enter Choice from the command line then use provided value to next process.
当用户从命令行提供 Enter Choice 时,然后将提供的值用于下一个过程。
If User not provided the Enter Choice from the command line then ask User to Enter Choice from the Menu.
如果用户未从命令行提供输入选项,则要求用户从菜单输入选项。
Demo:
演示:
File Name: 1.py
文件名: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."
Output:
输出:
Enter Choice given from the Command Line:
输入从命令行给出的选择:
$ python 1.py C
In Clear All event.
Menu
C Clear All
L Load Encrypted File
Q Quit
----------------
Enter Choice>
Enter Selection> q
$
No Command Line argument.
没有命令行参数。
$ 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
$
回答by erewok
Here's the thing, when you're learning a language like this, you can often get by pretty well with just printing out things you don't really understand.
事情是这样的,当你学习这样的语言时,你通常可以通过打印出你并不真正理解的东西来很好地学习。
Try this:
尝试这个:
Step 1) Make a program that looks like this:
步骤 1) 制作一个如下所示的程序:
import sys
if __name__ == '__main__':
for idx, arg in enumerate(sys.argv):
print("arg #{} is {}".format(idx, arg))
print len(sys.argv)
After that, run your program from the command line like this:
之后,从命令行运行您的程序,如下所示:
$ python3 test_script.py
Then, run it like this:
然后,像这样运行它:
$ python3 test_script.py somearg someother andanother etc "23908452359"
What you discover may be useful to perform this task you are looking to resolve.
您发现的内容可能对执行您希望解决的任务有用。
Lastly, "menu mode" sounds like the script is going to take input from the user. Thus, you'll need to use input()to do that. It also sounds like you need to come to some decision about when to use menu mode or not, which you've already started to do with your if-test above.
最后,“菜单模式”听起来像是脚本将从用户那里获取输入。因此,您需要使用input()来做到这一点。听起来您还需要决定何时使用菜单模式,您已经开始使用上面的 if 测试。
Experiment a bit, though, and you'll figure it out.
不过,稍微试验一下,你就会明白。
回答by Leland Barton
The instructions want the script to use the command line arguments to execute the script.
指令希望脚本使用命令行参数来执行脚本。
python script.py [arg1] [arg2] [arg3] ....
The args are accessible through sys.argv.
args 可通过 sys.argv 访问。
sys.argv = ['script.py', '[arg1]', '[arg2]', '[arg3]']
You will need to use a command line interface instead of the menu interface when args are present.
当存在 args 时,您将需要使用命令行界面而不是菜单界面。
回答by LinkBerest
Since you seem to be pretty new to python here's a simple example using your code. You'll have to complete the menu and the actual code for the menu options but it does use sys.argv
由于您似乎对 python 很陌生,这里有一个使用您的代码的简单示例。您必须完成菜单和菜单选项的实际代码,但它确实使用 sys.argv
import sys
def menu():
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>') #should get user input here
Done = True
if __name__=="__main__" :
if len(sys.argv) > 1 :
#Here if an argument is present run it or load the menu
print "run whatever option was entered on the commandline"
else:
menu()
回答by caynan
First of all you have to understand what argvis, try creating this script, and call it learning_argv.py
首先你必须了解什么argv是,尝试创建这个脚本,并称之为 learning_argv.py
import sys
print(sys.argv)
now try running the script like this:
现在尝试像这样运行脚本:
$ python3 learning_argv.py
$ python3 learning_argv.py a
$ python3 learning_argv.py a b c
$ python3 learning_argv.py AWESOME TEXT
See what argvis?
看看是什么argv?
What you're doing when you test if the length of argvis bigger than one, is basically testing if you're receiving anything beyond the script name.
当您测试长度argv是否大于 1时,您所做的基本上是测试您是否收到脚本名称以外的任何内容。
In the future, you could create a similar structure you created for your menu, to treat arguments sent directly from the command line.
将来,您可以为菜单创建一个类似的结构,以处理直接从命令行发送的参数。
take a look at this quick tutorialin order to better understand argv.
看看这个快速教程,以便更好地理解argv。

