我有一个脚本,意思是这样使用:
usage: installer.py dir [-h] [-v]
dir 是一个位置参数,定义如下:
parser.add_argument('dir', default=os.getcwd())
Run Code Online (Sandbox Code Playgroud)
我希望它dir是可选的:当它没有被指定时它应该是cwd.
不幸的是,当我没有指定dir参数时,我得到了Error: Too few arguments.
我注意到Python 2.7文档包含另一个命令行解析模块.除了getopt和optparse我们现在有argparse.
为什么还创建了另一个命令行解析模块?我为什么要用它而不是optparse?是否有我应该了解的新功能?
我已经阅读了这篇http://docs.python.org/release/2.6.2/library/optparse.html
但是我不太清楚如何在optparse中选择一个选项?
我试过设置"required = 1"但是我收到了一个错误:
无效的关键字参数:必需
我想让我的脚本需要--file选项由用户输入.我知道action当你不--file为其提供价值时,关键字会给你错误action="store_true".
我正在尝试学习如何使用python的argparse模块.目前我的python脚本是:
parser = argparse.ArgumentParser(description='My first argparse attempt',
add_help=True)
parser.add_argument("-q", action ="store", dest='argument',
help="First argument")
output = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
它将输出提供为:
usage: test.py [-h] [-q ARGUMENT]
My first argparse attempt
optional arguments:
-h, --help show this help message and exit
-q ARGUMENT First argument
Run Code Online (Sandbox Code Playgroud)
现在,让我们假设我希望我的-h or --help论点也打印出来usage example.喜欢,
Usage: python test.py -q "First Argument for test.py"
Run Code Online (Sandbox Code Playgroud)
我的目的是打印上面的用法示例以及-h参数的默认内容,以便用户可以基本了解如何使用test.pypython脚本.
那么,这个功能是否在argparse模块中内置.如果不是什么是正确的方法来解决这个问题.
我想通过他们的名字(像kwargs这样的东西)向脚本发送参数.我试过这样的事情,但它没有做我想要的事情:(假设它是用script.py写的)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
然后用commant行写:script.py name = david
另外一件事,假设我在argparse中有几个命名参数如果我不按照它们被声明的顺序发送它们它还能运行吗?
我正在解决这个问题的答案:Python Interactive Shell Type Application
我的代码看起来像这样
def main():
while True:
s = input('> ')
if s == 'hello':
print('hi')
if s == 'exit':
break
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
如果我运行它,并键入你好,我得到
File "<string>", line 1, in <module>
NameError: name 'hello' is not defined
Run Code Online (Sandbox Code Playgroud)
我应该如何监听文本,并根据结果调用不同的函数?
python ×6
argparse ×4
command-line ×2
getopt ×1
interactive ×1
optparse ×1
shell ×1
undefined ×1