温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中sys.arg如何使用

发布时间:2021-07-05 16:40:41 来源:亿速云 阅读:290 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关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 &ndash;version 输出结果为:version 1.2

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

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI