Python command line parameters and code compilation and publishing as executable files

1. Python command line parameters

$ python test.py arg1 arg2 arg3

1.1 In Python, sys.argv of sys can also be used to obtain command line parameters

sys.argv is a list of command line arguments.
len(sys.argv) counts the number of command line arguments.
Note: sys.argv[0] means the script name.

The sample test.py file code is as follows:

#!/usr/bin/python3
import sys
print ('参数个数为:', len(sys.argv), '个参数。')
print ('参数列表:', str(sys.argv))
print ('脚本名:', str(sys.argv[0]))

Execute the above code, the output is:

$ python3 test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
脚本名: test.py

1.2 Python provides the getopt module to obtain command line parameters.

The getopt module is a module that specifically handles command-line parameters, and is used to obtain command-line options and parameters, that is, sys.argv. Command-line options make the parameters of the program more flexible. The short option mode - and the long option mode -- are supported. This module provides two methods and an exception handler to parse command line arguments. How to use getopt, first import key modules:

import sys
import getopt

When using it, since the getopt function is a function in the getopt package, use getopt.getopt(…) in this way.
The getopt.getopt method is used to parse the command line parameter list, the syntax format is as follows:

getopt.getopt(args, shortopts, longopts=[])

Method parameter description:

  • args: is a list of parameters. Just pass in the sys.args[1:] slice directly.
  • shortopts: This parameter is a string, and the "short options" that need to be parsed can be written together next to each other. The "short options" here refer to the options starting with '-'. It supports a single letter, even if you write a parameter like -test, -t and est can be recognized by getopt, and est will be used as the parameter of the -t option. So suppose you want to support three short options "-h -i -o", shortopts can be written as "hio". If one of the short options wants to accept parameters, such as "-h -i inputfile -o outputfile", then you need to add a ":" colon after the letter to become "hi: o:"
  • longopts=[]: This parameter is a list, because each long option has multiple letters, it is impossible to express them all in one string like the short option. The so-called long option is the option starting with "-", such as --usr --ifile --ofile, etc. When passing parameters, it is written as ['--user', '--ifile', '--ofile'], if a certain If the option needs to accept parameters, add an equal sign "=" after it, such as ['–user', '–ifile=', '–ofile='].

There are two return values:

  • opts: There is a list, and the list is in the format of tuples (opt, value). For example, "-h -i inputfile -o outputfile" above is [('-h', ''), ('-i', 'inputfile'), ('-o', 'outputfile')] like this return value. Long options and short options and their respective parameters will be placed here in order. When used, it can be traversed in the way of for opt, val in opts:. It is worth noting that in the returned opt, '-' and '–' are preserved. In addition, when the long option entered by the user is not finished, it will be automatically completed. For example, if the user enters --u, it will be automatically completed as --user by getopt. This needs attention (unless there are two long options with the same beginning, it is impossible to determine which one).
  • args: If the user enters too much information, in addition to the long option and short option and the parameters of their respective options, there are some other unknown parameters, which will be placed here.

Next, we define a site() function, and then input the site name and website url through the command line, which can be abbreviated as n and u.
Example demonstrating short options:

import sys
import getopt

def site():
    name = None
    url = None

    argv = sys.argv[1:]

    try:
        opts, args = getopt.getopt(argv, "n:u:")  # 短选项模式

    except:
        print("Error")

    for opt, arg in opts:
        if opt in ['-n']:
            name = arg
        elif opt in ['-u']:
            url = arg

    print(name + " " + url)

site()

To test the above code, enter on the command line:

python3 test.py -n RUNOOB -u www.runoob.com

The output is:

RUNOOB www.runoob.com

Examples of long options

import sys
import getopt
 
def site():
    name = None
    url = None
 
    argv = sys.argv[1:]
 
    try:
        opts, args = getopt.getopt(argv, "n:u:",  
                                   ["name=",
                                    "url="])  # 长选项模式
     
    except:
        print("Error")
 
    for opt, arg in opts:
        if opt in ['-n', '--name']:
            name = arg
        elif opt in ['-u', '--url']:
            url = arg
     
 
    print( name + " " + url)
 
site()

To test the above code, enter on the command line:

python3 test.py -n RUNOOB -u www.runoob.com

The output is:

RUNOOB www.runoob.com

Reference:
[1] Python3 command line parameters
[2] Detailed explanation of getopt function in python
[3] Detailed usage of getopt in Python

2. Compile and publish the Python code as an executable file

2.1 Packaging tool Pyinstaller

PyInstaller actually packs the python parser and your own script into an executable file, which is completely different from compiling it into real machine code, so don't expect that packaging into an executable file will improve operating efficiency, on the contrary it may It will reduce the running efficiency, and the advantage is that there is no need to install python and the libraries that your script depends on on the runner's machine.

2.2 Install Pyinstaller

If the network is stable, you can usually install it directly with the following command:

pip install pyinstaller

To check whether pyinstaller is successfully installed, you only need to execute one of the following commands:

pyinstaller --version
pyinstaller -v

2.3 Pyinstaller parameter function

-F 表示生成单个可执行文件
-D –onedir 创建一个目录,包含exe文件,但会依赖很多文件(默认选项)
-w 表示去掉控制台窗口,这在GUI界面时非常有用。不过如果是命令行程序的话那就把这个选项删除吧
-c –console, –nowindowed 使用控制台,无界面(默认)
-p 表示你自己自定义需要加载的类路径,一般情况下用不到
-i 表示可执行文件的图标
其他参数,可以通过pyinstaller --help查看

2.4 start packaging

Enter the directory where the script that python needs to package is located, and then execute the following command:

pyinstaller -F test.py

For details, see:
[1] How Python generates an executable .exe file
[2] Python code compiled and released as an executable file
[3] How to package a Python program into a linux executable file

Supongo que te gusta

Origin blog.csdn.net/wokaowokaowokao12345/article/details/128796529
Recomendado
Clasificación