command line arguments in Python

Source: Internet
Author: User
Tags function prototype python script

Command-line arguments in Python

Python has a module SYS,SYS.ARGV this property provides access to command-line arguments. A command-line argument is a parameter other than the program name when a program is called.

SYS.ARGV is a list of command-line arguments

Len (SYS.ARGV) is the number of command-line arguments

Let's use a simple example to illustrate this.

#!/usr/bin/python#coding:utf-8import SYS   # #加载sys这个模块. For I in range (len (SYS.ARGV)):    print "%d parameter is:%s"% (I,sys.argv[i]) print

Run the above script:

Python argv.py 1 2 3

The results are as follows:

The No. 0 parameter is: argv.py

The 1th parameter is: 1

The 2nd parameter is: 2

The 3rd parameter is: 3

Running results from the above script we can see that the first argument is that the script name itself is the No. 0 parameter. The rest of the analogy.

With this sys.argv parameter we can pass some arguments to the script that we want to use.

Another common module Os.path can be used to complete the operation of the path. It provides functions to manage and manipulate various parts of the file path, get file or subdirectory information, and file path query operations.

Some of the functions commonly used in OS modules are listed below:

Function Name: effect:

Os.mkfifo (' Path/filename ')/os.mknod (' Path/filename ', mode,device) create Named pipes/create File system nodes

Os.remove (' path/filename ') Delete file

Os.rename (' path/filename1 ', ' path/filename2 ')/renames () renaming files

Os.stat (' path/filename ') returns file information

Os.symlink (' Path/filename ', ' path/ln_filename ') create Symbolic Links

Os.utime () Update timestamp

Os.tmpfile () Create and open (' W+b ') a new temporary file

Os.walk () generates all filenames under a directory tree

Directory/Folder

Os.chdir ()/fchdir () change the current working directory/change the current working directory with a file descriptor

Chroot () Changes the root directory of the current process

Listdir () lists files for the specified directory

GETCWD ()/getcwdu () returns the current working directory/function same, but returns a Unicode object

mkdir ()/makedirs () Create a directory/create a multi-level directory

RmDir ()/removedirs () Delete directory/delete multi-level directory

Access/Permissions

Access () Verify permission mode

chmod () Change permission mode

Chown ()/lchown () changes ower and group ID/function the same, but does not track links

Umask () Set default permission mode

File descriptor Operations

Open () Underlying operating system open (for files, use the standard built-in open () function)

Read ()/write () reads/writes data according to the file descriptor

The DUP ()/dup2 () Copy file descriptor/function is the same, but is copied to a file descriptor device number.

Makedev () Create an original device number from the major and minor device numbers

Major ()/minor () get the Major/minor device number from the original device number

Here are some of the functions that are accessed by path names in the Os.path module

function Description

Os.path.basename () Remove directory path, return file name

Os.path.dirname () Remove file name, return directory path

Os.path.join () combines parts of the separation into one path name

Os.path.split () return (DirName (), basename ()) tuple

Os.path.splitdrive () return (dirvename,pathname) tuple

Os.path.splitext () return (filename,extension) tuple

Information

Getatime () returns the last access time

Getctime () returns file creation time

Getmtime () returns the last file modification time

GetSize () returns the file size (in bytes)

Inquire

Exists () specifies whether the path (file or directory) exists

Isabs () Specifies whether the path is an absolute path

Isdir () Specifies whether the path exists and is a directory

Isfile () Specifies whether the path exists and is a file

Islink () Specifies whether the path exists and is a symbolic link

Ismount () Specifies whether the path exists and is a mount point

Samefile () Two path names point to the same file

This article describes the SYS in Python and the getopt module handles command-line arguments

If you want to pass parameters to the Python script, what is the corresponding argc in Python, argv (command-line arguments for the C language)?
Module Required: SYS
Number of parameters: Len (SYS.ARGV)
脚本名:    sys.argv[0]
参数1:     sys.argv[1]
参数2:     sys.argv[2]


test.py

Import sysprint "script name:", sys.argv[0]for I in range (1, Len (SYS.ARGV)):    print "parameter", I, Sys.argv[i]

>>>python test.py Hello World

Script Name: test.py
Parameter 1 Hello
Parameter 2 World

Use command-line options in Python:
For example we need a convert.py script. It works by processing one file and outputting the processed results to another file.
The script is required to meet the following criteria:
1. Use the-I-O option to distinguish whether the parameter is an input file or an output file.
>>> python convert.py-i inputfile-o outputfile
2. If you do not know what parameters convert.py need, print out the help information with-H
>>> python convert.py-h

getopt function Prototype:
Getopt.getopt (args, options[, long_options])

convert.py

Import sys, getoptopts, args = Getopt.getopt (sys.argv[1:], "Hi:o:") input_file= "" Output_file= "" for op, value in opts:    if op = = "-I":        input_file = value    elif op = = "-O":        output_file = value    elif op = = "-H":        usage () 
   sys.exit ()

代码解释:
a) sys.argv[1:]为要处理的参数列表,sys.argv[0]为脚本名,所以用sys.argv[1:]过滤掉脚本名。
b) "hi:o:": 当一个选项只是表示开关状态时,即后面不带附加参数时,在分析串中写入选项字符。当选项后面是带一个附加参数时,在分析串中写入选项字符同时后面加一个":"号。所以"hi:o:"就表示"h"是一个开关选项;"i:"和"o:"则表示后面应该带一个参数。
c) 调用getopt函数。函数返回两个列表:opts和args。opts为分析出的格式信息。args为不属于格式信息的剩余的命令行参数。opts是一个两元组的列表。每个元素为:(选项串,附加参数)。如果没有附加参数则为空串‘‘。

getopt函数的第三个参数[, long_options]为可选的长选项参数,上面例子中的都为短选项(如-i -o)
长选项格式举例:
--version
--file=error.txt
让一个脚本同时支持短选项和长选项
getopt.getopt(sys.argv[1:], "hi:o:", ["version", "file="])

command line arguments in Python

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.