Python学习之四sys.argv

时间:2022-09-01 21:26:16


一、将如下的代码保存为opennote.py

import sys,os
os.system(sys.argv[1])
</span></span>

命令行窗口执行:opennote.py notepad

神奇的效果出现了,自动打开的记事本程序;

解析:sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码本身的(py文件)文件路径;sys.argv[1]表示第一个参数。上例中就是notepad,所以它的执行效果跟我们在命令行窗口直接敲入notepad后回车的效果是一样的。

二、更加复杂的例子,

知识点:

1、文件中有打印中文的注释,需要在文件的第二行加入# -*- coding: utf8 -*-的注释,否则会报如下错误:

SyntaxError: Non-ASCII character '\xe6' in file C:\Users\honghao.jhh\Desktop\aa.py on line 18, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

2、缩进时是四个空格或8个空格进行缩进,否则会报缩进的错误:

IndentationError: expected an indented block

3、os.path.exists(filename)方法判断某个文件是否在当前目录存在。


argv.py和help.txt请保存在一个目录:

help.txt:

      This is the text from the help.txt
      This program prints files to the standard output.
      Any number of files can be specified so long as the file exists.
      Options include,other option will be undone:
      --version : Prints the version number
      --help    : Display this help</span>

argv.py

#!/usr/local/bin/env python
# -*- coding: utf8 -*-</span>
#@author
#@Date:2015 05.31
#@Location:Hangzhou zhejiang library

import sys
import os
def readfile(filename):
    '''Print a file to the standard output.'''
    f = file(filename)
    while True:
          line = f.readline()
          if len(line) == 0:
             break
          print line,
    f.close()

# 打印输入的命令
print 'you command is :%s ' %(''.join(sys.argv))
if len(sys.argv) <=1:
    #sys.argv=0 is impossible,if sys.argv =1,it stand for the name of the py file itself.
    print 'No action specified,Please add more parameter to your command'
    sys.exit()
if sys.argv[1].startswith('--'):
   # fetch sys.argv[1] but without the first two characters
   option = sys.argv[1][2:]
   if option == 'version':
      print 'Version 1.0 @2015.05.31 by jinhonghao'
   elif option == 'help':
      print '''
      This program prints files to the standard output.
      Any number of files can be specified so long as the file exists.
      Options include,other option will be undone:
      --version : Prints the version number
      --help    : Display this help'''
   else:
       print 'Unknown option,Please check your parameter!'
       sys.exit()
else:
    #if parameters are not --help and --version,when the file is exists,it will be printed ,or give the hint.
    for filename in sys.argv[1:]:
	    #check whether the file exists
        if os.path.exists(filename) :
            readfile(filename)
        else:
            print "\nWarnning :%s not exists!!Please check your parameter!"%(filename)</span>
执行结果:

Command one:argv.py --version

you command is :C:\Users\honghao.jhh\Desktop\aa.py--version
Version 1.0 @2015.05.31 by jinhonghao

Command two:argv.py --help

you command is :C:\Users\honghao.jhh\Desktop\aa.py--help

      This program prints files to the standard output.
      Any number of files can be specified so long as the file exists.
      Options include,other option will be undone:
      --version : Prints the version number
      --help    : Display this help

Command three:argv.py --pp

you command is :C:\Users\honghao.jhh\Desktop\aa.py--pp
Unknown option,Please check your parameter!

Command three:argv.py help.txt

you command is :C:\Users\honghao.jhh\Desktop\aa.pyhelp.txt
      This is the text from the help.txt
      This program prints files to the standard output.
      Any number of files can be specified so long as the file exists.
      Options include,other option will be undone:
      --version : Prints the version number
      --help    : Display this help