大家现正在学习命令行参吗?用没用到过getopt呢?今天小编,就不跟大家聊很多的内容了,直接给大家介绍今天的文章主题,就是关于前文所提到的getopet,小伙伴们对此有没有什么了解呢?没有了解的小伙伴也不必担心,因为下面小编给大家浓缩了这个知识点的精华,看一遍,就可以快速上手了。
实例
假定我们创建这样一个脚本,可以通过命令行向脚本文件传递两个文件名,同时我们通过另外一个选项查看脚本的使用。
脚本使用方法如下:
usage: test.py -i <inputfile> -o <outputfile>
test.py 文件代码如下所示:
import sys, getopt def main(argv): inputfile = '' outputfile = '' try: opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="]) except getopt.GetoptError: print 'test.py -i <inputfile> -o <outputfile>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'test.py -i <inputfile> -o <outputfile>' sys.exit() elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-o", "--ofile"): outputfile = arg print '输入的文件为:', inputfile print '输出的文件为:', outputfile if __name__ == "__main__": main(sys.argv[1:])
执行以上代码,输出结果为:
$ python test.py -h usage: test.py -i <inputfile> -o <outputfile> $ python test.py -i inputfile -o outputfile 输入的文件为: inputfile 输出的文件为: outputfile
好啦,如果在碰到以上模块的使用方法,一定要看下这篇文章内容哦~都是所有疑难问题的解决集锦呢~小伙伴们仔细再看几遍吧,如果还想了解其他内容,就到教程中心浏览吧~
常见问题FAQ
- 免费下载或者VIP会员专享资源能否直接商用?
- 本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
- 提示下载完但解压或打开不了?
- 找不到素材资源介绍文章里的示例图片?
- 模板不会安装或需要功能定制以及二次开发?
发表评论
还没有评论,快来抢沙发吧!