189 8069 5689

Python中sys.arg如何使用

这篇文章将为大家详细讲解有关Python中sys.arg如何使用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

公司主营业务:成都网站设计、网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联推出蒲江县免费做网站回馈大家。

1、使用sys.argv[]的一简单实例,

import sys,os   os.system(sys.argv[1])   import sys,os  os.system(sys.argv[1])

这个例子os.system接收命令行参数,运行参数指令,保存为sample1.py,命令行带参数运行sample1.py notepad,将打开记事本程序。

2、这个例子是简明Python教程上的,明白它之后你就明白Python sys.arg使用了。

import sys   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, # notice comma 分别输出每行内容   if.close()   # Script starts from here   if len(sys.argv) < 2:   print 'No action specified.'   sys.exit()   15if sys.argv[1].startswith('--'):   option = sys.argv[1][2:]   # fetch sys.argv[1] but without the first two characters   if option == 'version': #当命令行参数为-- version,显示版本号   print 'Version 1.2'   elif option == 'help': #当命令行参数为--help时,显示相关帮助内容   print '''''\   This program prints files to the standard output.   Any number of files can be specified.   Options include:   --version : Prints the version number   --help : Display this help'''   else:   print 'Unknown option.'   sys.exit()   else:   for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容   readfile(filename)   import sys  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, # notice comma 分别输出每行内容  f.close()  # Script starts from here  if len(sys.argv) < 2: print 'No action specified.'  sys.exit()  if sys.argv[1].startswith('--'):  option = sys.argv[1][2:]  # fetch sys.argv[1] but without the first two characters  if option == 'version': #当命令行参数为-- version,显示版本号  print 'Version 1.2'  elif option == 'help': #当命令行参数为--help时,显示相关帮助内容  print '''\  This program prints files to the standard output.  Any number of files can be specified.  Options include:  --version : Prints the version number  --help : Display this help'''  else:  print 'Unknown option.'  sys.exit()  else:  for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容  readfile(filename)

保存程序为sample.py.我们验证一下:

  • Python数据转换实现代码深入分析

  • 深入探讨Python序列神奇之处

  • Python for in实际应用代码操作方法

  • Python Thread类主要功能介绍

  • Python二维数组实际应用方法浅析

< !--[if !supportLists]-->1) < !--[endif]-->命令行带参数运行:sample.py –version 输出结果为:version 1.2

< !--[if !supportLists]-->2) < !--[endif]-->命令行带参数运行:sample.py –help 输出结果为:This program prints files……

< !--[if !supportLists]-->3) < !--[endif]-->在与sample.py同一目录下,新建a.txt的记事本文件,内容为:test argv;命令行带参数运行:sample.py a.txt,输出结果为a.txt文件内容:test argv,这里也可以多带几个参数,程序会先后输出参数文件内容。

关于Python中sys.arg如何使用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


分享标题:Python中sys.arg如何使用
URL地址:http://cdxtjz.cn/article/pjgdjp.html

其他资讯