简体   繁体   English

argv与raw_input

[英]argv vs. raw_input

I know that when using argv I have to type the file as an argument (ex: python ex15.py ex15_sample.txt ) and when using raw_input I enter the filename as an input. 我知道使用argv必须输入文件作为参数(例如: python ex15.py ex15_sample.txt ),使用raw_input要输入文件名作为输入。

But I can't seem to find out why one way of getting the filename would be better than another. 但是我似乎无法找出为什么一种获取文件名的方法会比另一种更好的方法。 Can someone explain why? 有人可以解释为什么吗?

That's because you generally should avoid interactive user input if it's not a key feature. 那是因为如果这不是关键功能,通常应该避免交互式用户输入。 In your example: Reading from stdin or the command line allows to combine different programs and run them in scripts and so on. 在您的示例中:从stdin或命令行读取允许组合不同的程序并在脚本中运行它们,依此类推。

Imagine you execute a lot of code and sit in front of the screen waiting for the input request to come. 想象一下,您执行了很多代码,坐在屏幕前等待输入请求的到来。 Wasn't it better to specify all relevant information on the command line and to go and prepare a cup of coffee instead? 在命令行上指定所有相关信息并去准备一杯咖啡不是更好吗?

What you could do: 您可以做什么:

  • Check if len(argv) > 1 检查len(argv)是否> 1
  • If so, use argv[1] as the file name 如果是这样,请使用argv [1]作为文件名
  • If not, ask the user. 如果不是,请询问用户。

This adds a nice feature to your program: You can either specify the file name on the command line or enter it in an interactive mode. 这为您的程序增加了一个不错的功能:您可以在命令行上指定文件名,也可以以交互方式输入文件名。

Try this: 尝试这个:

try:
    fn = argv[1]

except IndexError:
    fn = raw_input("filename > ")

As part of command line argument input, a user can submit system calls and that could crash your program. 作为命令行参数输入的一部分,用户可以提交系统调用,这可能会使您的程序崩溃。 Eg a user can issue an ls command. 例如,用户可以发出ls命令。 The system executes that command regardless of what your program is supposed to do. 无论您的程序打算做什么,系统都会执行该命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM