为什么我们需要使用' argparse'在python中与命令提示符互动?
最近,我在 python 中遇到了“argparse”库的使用。它用于获取输入和输出目录的位置。 使用“argparse”的需要是什么,为什么我们不能只使用 input() 来获取目录的位置或命令行中的任何用户输入?
我尝试在命令行中使用 input() 获取用户输入,并且它有效。 我读了“Python 中的 stdin 和 sys.argv 有什么区别?”的答案它并没有帮助解决我对何时使用 input() 以及何时使用 argparse 的疑问。
Recently, I came across the use of 'argparse' library in python. It was used to get the location of input and output directories.
What is the need of using 'argparse', why can't we just use input() to get the location of directories or any user input in the command line?
I tried getting the user input using input() in the command line, and it worked.
I read the answer to 'What's the difference between stdin and sys.argv in python?' and it did not help resolve my doubt of when to use input() and when to use argparse.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
想象一个需要输入路径才能运行的程序。让我们看看如何使用
argparse
和input
来使用它。首先,
argparse
你可以这样使用它:
如果我不是 100% 确定路径,我可以使用 shell 的制表符补全来帮助我,
这很有帮助!如果我想再次执行此操作,我只需按“向上”箭头,它就在我的命令提示符上再次执行!
现在,让我们看看使用
input
你可能会这样使用它
如果我不知道路径怎么办?我可以使用制表符补全吗?
哦不!它只是在文件名中插入了一个选项卡 - 我没有得到任何帮助。
如果我想再次执行相同的命令怎么办?我按向上键,然后必须在运行之前重新输入文件路径。想象一下,您正在调试此脚本,并且需要一遍又一遍地运行它 - 重新输入路径将很快变得陈旧。
input
仅当您想强制脚本进行交互时才有用,例如您想说“您确定要继续吗?[y/N]”。否则,最好在命令行上接受运行时参数,以充分利用 shell 提供的功能,并使重新执行(以及在另一个脚本中使用您的脚本)变得更加简单。Imagine a program that needs an input path in order to operate. Let's examine how using this might look with
argparse
andinput
.First,
argparse
You might use it like this:
If I wasn't 100% sure of the path, I could use my shell's tab-completion to help me out
That was helpful!! If I want to execute this again, I can just press the "up" arrow and it's right there on my command prompt to be executed again!
Now, let's look at using
input
You might use it like this
What if I didn't know the path? Could I use tab completion?
Oh no! It just inserted a tab into the filename - I get no help.
What if I want to execute the same command again? I press up, and then have to re-type the file path before running. Imagine you are debugging this script and need to run it over and over again - re-typing the path will get old very fast.
input
is really only useful if you want to force a script to be interactive, like if you want to say "Are you sure you want to proceed? [y/N]". Otherwise, it's best to accept runtime parameters on the command line to take full advantage of what the shell has to offer as well as make it so that re-execution (and using your script in another script) is much simpler.