Python sys.argv[] Usage

Source: Internet
Author: User

Sys.argv[] is used to get command line arguments, Sys.argv[0] represents the code itself file path, so the parameters starting from 1, the following two examples illustrate:

1. A simple example of using sys.argv[]

Import Sys,os  Os.system (sys.argv[1])  

This example Os.system receive command line arguments, run parameter directives, save as sample1.py, command line with parameters run sample1.py Notepad, will open the Notepad program.

2, this example is a concise Python tutorial.

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 P Rint Line, # Notice comma outputs each row of content F.close () # Script starts from here if Len (SYS.ARGV) < 2:print ' No Act      Ion specified. ' Sys.exit () If Sys.argv[1].startswith ('--'): option = sys.argv[1][2:] # fetch SYS.ARGV[1] but without the first Characters if option = = ' Version ': #当命令行参数为--version, showing the revision number print ' version 1.2 ' elif option = = ' He LP ': When #当命令行参数为--help, display the relevant Help content print ""/This program prints files to the standard output. Any number of the files can be specified. Options include:--version:prints The version number--help:display this help ' Else:print ' Unk      Nown option. ' Sys.exit () else:for filename in sys.argv[1:]: #当参数为文件名时, incoming ReadFile, read its contents ReadFile (FilenamE   

Save the program as sample.py. Let's verify that:

1) command line with parameters run: Sample.py–version output is: Version 1.2

2) command line with parameters run: Sample.py–help output is: This program prints files ...

3) in the same directory as sample.py, create a new a.txt Notepad file with the content: Test argv; command line with parameters run: sample.py a.txt, the output is a.txt file content: Test argv, here can also take a few more parameters, The program will output the contents of the parameter file successively.

Python sys.argv[] Usage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.