看到别人执行一个支持命令行参数的python文件,瞬间觉得高大上起来、牛逼起来,那么如何编写一个带命令行参数的python脚本呢?不用紧张,下面将简单易懂地让你学会如何让自己的python脚本,支持命令行参数。

首先你要知道python中的sys模块的一些功能:

import sys

print "the number of python program's argument:",len(sys.argv)

print "the value of every argument is ",str(sys.argv)

#上述程序的文件名sysargv.py
python sysargv.py argv1 argv2 argv3 argv4
the number of python program's argument: 5
the value of every argument is ['sysargv.py', 'argv1', 'argv2', 'argv3', 'argv4']

其次,python程序使用命令行参数,必不可少的模块,就是getopt 模块,先看看一段代码

getopt.getopt(args, options[, long_options])
import getopt
args = '-a -b -cfoo -d bar a1 a2'.split()
args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
optlist, args = getopt.getopt(args, 'abc:d:')
optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
args
['a1', 'a2']

使用long_options

s = '--condition=foo --testing --output-file abc.def -x a1 a2'
args = s.split()
args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
optlist, args = getopt.getopt(args, 'x', ['condition=', 'output-file=', 'testing'])
optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
args
['a1', 'a2']

最后实战一个例子吧!

import getopt,sys

def main():
try:
opts,args=getopt.getopt(sys.argv[1:],"hi:o:v",["help","infile=","outfile="])
except getopt.GetoptError as error:
print str(error)
usage()
sys.exit(2)
infile=None
output=None
verbose=False
for key,value in opts:
if key=="-v":
verbose=True
elif key in ("-h","--help"):
print "sysargv.py -i <inputfile> -o <outputfile>"
print "or sysargv.py --infile <inputfile> --outfile <outputfile>" elif key in ("-i","--infile"):
infile = value
elif key in ("-o","--outfile"):
output= value
print "inputfile:", infile
print "outputfile:", output
print verbose
if __name__=="__main__":
main()

测试结果:

C:\Python27>python sysargv.py --help
sysargv.py -i <inputfile> -o <outputfile>
or sysargv.py --infile <inputfile> --outfile <outputfile>
inputfile: None
outputfile: None
False C:\Python27>python sysargv.py -h
sysargv.py -i <inputfile> -o <outputfile>
or sysargv.py --infile <inputfile> --outfile <outputfile>
inputfile: None
outputfile: None
False C:\Python27>python sysargv.py -i "inputfile1" -o "ouputfile2"
inputfile: inputfile1
outputfile: ouputfile2
False C:\Python27>python sysargv.py -i "inputfile1"
inputfile: inputfile1
outputfile: None
False C:\Python27>python sysargv.py -o "outputfile1"
inputfile: None
outputfile: outputfile1
False C:\Python27>python sysargv.py -o "outputfile1" -v
inputfile: None
outputfile: outputfile1
True C:\Python27>python sysargv.py --infile "inputfile" --outfile "outputfile1" -v
inputfile: inputfile
outputfile: outputfile1
True

如何编写一个带命令行参数的Python文件的更多相关文章

  1. VS2013中带命令行参数的调试方法---C++

    今天先记录一下(也是传说中大神喜欢装逼的comment line)c++中向主函数int main(int argc,char** argv )传递4中方法,欢迎添加新方法, 然后可以参考别人写的很好 ...

  2. vscode带命令行参数进行调试

    vscode带命令行参数进行调试 2.输入代码 { // 使用 IntelliSense 了解相关属性. // 悬停以查看现有属性的描述. // 欲了解更多信息,请访问: https://go.mic ...

  3. VS2013 带命令行参数的调试问题 解决方案

    int main(int argc,char* argv[]) argc是命令行总的参数个数,argv[]是argc个参数,其中第0个参数是程序的全名,以后的参数命令行后面跟的用户输入的参数 比如:  ...

  4. 3-2带命令行参数的Java

    命令行参数: 主方法Main 小括号里面的内容就是命令参数: String[] args class ArgsDemo{ public static void main(String[] args){ ...

  5. python 命令行参数,以及文件操作

    #demo.py #!/usr/bin/python import sys print sys.argv #python demo.py 11 22 33 44 55 ['demo.py', '11' ...

  6. 命令行参数处理-getopt()和getopt_long()

    在实际编程当中,自己编写代码处理命令行参数是比较麻烦且易出错的.一般我们会直接使用getopt()和getopt_long()函数,下文将介绍具体的使用方法. getopt() getopt()用于处 ...

  7. shell 命令行参数(getopt和getopts)

    getopt 命令 使用getopt命令,可以解析任何命令行选项和参数,但是用法比较复杂.getopt的命令用法如下: $ getopt --help 用法: getopt optstring par ...

  8. python命令行参数处理模块 optparse 使用参考

    from optparse import OptionParser parser = OptionParser() parser.add_option( '-f', '--file', dest='f ...

  9. tensorflow命令行参数:tf.app.flags.DEFINE_string、tf.app.flags.DEFINE_integer、tf.app.flags.DEFINE_boolean

    tf 中定义了 tf.app.flags.FLAGS ,用于接受从终端传入的命令行参数,相当于对Python中的命令行参数模块optpars(参考:python中处理命令行参数的模块optpars)做 ...

随机推荐

  1. Django models Fild详解

    本文参考自:django官方文档models/field 在model中添加字段的格式一般为:  field_name = field_type(**field_options) 一  field o ...

  2. (转)html中 cookie设置

    box=="checkBox  '是否记住用户密码'": window.onload=function init() {    var box = getCookie(" ...

  3. vue2.0实践 —— Node + vue 实现移动官网

    简介 使用 Node + vue 对公司的官网进行了一个简单的移动端的实现. 源码 https://github.com/wx1993/node-vue-fabaocn 效果 组件 轮播图(使用 vu ...

  4. [刷题]Codeforces 794C - Naming Company

    http://codeforces.com/contest/794/problem/C Description Oleg the client and Igor the analyst are goo ...

  5. 反序列py脚本分享(原创)

    代码如下: #!/usr/bin/env python # coding=utf-8 import socket import sys import requests import base64 im ...

  6. rabbitmq安装Management Plugin

    运行和安装Rabbitmq Management的步骤如下: 1.进入Rabbitmq安装目录,运行rabbitmq-plugins enable rabbitmq_management 2.运行ra ...

  7. ASP.NET Core实现类库项目读取配置文件

    前言 之前继续在学习多线程方面的知识,忽然这两天看到博问中有个园友问到如何在.net core类库中读取配置文件,当时一下蒙了,这个提的多好,我居然不知道,于是这两天了解了相关内容才有此篇博客的出现, ...

  8. Vue中comoputed中的数据绑定

    Vue中的数据实现响应式绑定是在初始化的时候利用definePrototype的定义set和get过滤器,在进行组件模板编译时实现water的监听搜集依赖项,当数据发生变化时在set中通过调用dep. ...

  9. Natas Wargame Level 12 Writeup(文件上传漏洞)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAsQAAAChCAYAAADA86lDAAAABHNCSVQICAgIfAhkiAAAIABJREFUeF

  10. Tomcat8-源码编译及开发

    前言 下载Tomcat8源码进行分析,最好的方式,可以编译及运行,从网上查询了很多方式,总是不能完整的运行,由于本人采用idea编辑器,所以喜欢maven的方式,所以综合了网上的多种方案,最终可以在i ...