optparse 和字符串
尝试学习如何使用 outparse。所以情况是这样的,我想我的设置是正确的,只是如何设置我的选项有点......让我困惑。基本上我只是想检查我的文件名以查看是否有特定的字符串。
例如:
python script.py -f filename.txt -a hello simple
我希望它返回类似...
Reading filename.txt....
The word, Hello, was found at: Line 10
The word, simple, was found at: Line 15
这是我到目前为止所拥有的,我只是不知道如何正确设置它。抱歉问了愚蠢的问题:P。提前致谢。
这是迄今为止的代码:
from optparse import OptionParser
def main():
usage = "useage: %prog [options] arg1 arg2"
parser = OptionParser(usage)
parser.add_option_group("-a", "--all", action="store", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("not enough number of arguments")
#Not sure how to set the options...
if __name__ == "__main__":
main()
Trying to learn how to use outparse. So here is the situation, I think I got my setup correct its just how to set my options is kinda... confusing me. Basically I just want to check my filename to see if there are specific strings.
For example:
python script.py -f filename.txt -a hello simple
I want it to return something like...
Reading filename.txt....
The word, Hello, was found at: Line 10
The word, simple, was found at: Line 15
Here is what I have so far, I just don't know how to set it up correctly. Sorry for asking silly questions :P. Thanks in advance.
Here is the code thus far:
from optparse import OptionParser
def main():
usage = "useage: %prog [options] arg1 arg2"
parser = OptionParser(usage)
parser.add_option_group("-a", "--all", action="store", type="string", dest="search_and", help="find ALL lines in the file for the word1 AND word2")
(options, args) = parser.parse_args()
if len(args) != 1:
parser.error("not enough number of arguments")
#Not sure how to set the options...
if __name__ == "__main__":
main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
OptionParser.add_option()
...add_option_group()
并没有按照您的想法做...这是一个完整的示例,其精神是你在…注意--all
依赖于逗号分隔值…这使得它更容易,而不是使用空格分隔(这需要引用的选项值>--all
另请注意,您应该检查 。显式地使用
options.search_and
和options.filename
,而不是检查args
的长度使用相同的示例,使用以下命令调用脚本... <代码>python script.py -f 文件名.txt -a 你好,简单
You should use
OptionParser.add_option()
...add_option_group()
isn't doing what you think it does... this is a complete example in the spirit of what you're after... note that--all
relies on comma-separating the values... this makes it easier, instead of using space separation (which would require quoting the option values for--all
.Also note that you should check
options.search_and
andoptions.filename
explicitly, instead of checking the length ofargs
Using your same example, invoke the script with...
python script.py -f filename.txt -a hello,simple