• notice
  • Congratulations on the launch of the Sought Tech site

How to implement a tool for batch packaging programs using Python

This article mainly introduces the relevant knowledge of "How to use Python to implement tools for batch packaging programs". The editor will show you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "How to use Python to achieve batch packaging" Program Tools" article can help you solve problems.

The program calls the cmd command

The pyinstaller packager needs to use the cmd command. Here is a brief description of the common methods of calling the cmd command.

os.system()

system() is a built-in function of the os module, which can convert strings into commands and execute them at the terminal:

def system (*args, **kwargs) : # real signature unknown
     """ Execute the command in a subshell. """
     pass

Using this method is very simple, just put the command to be executed in the function as a string:

import  os os .system(f 'pyinstaller -F -w D:\program.py' )

The cmd window will not appear when the command is executed, it is displayed in the IDE by default, and the generated files are in the same directory by default:

How to use Python to implement a tool for batch packaging programs

os.popen()

The popen() method is also a built-in function of the os module, which is implemented by means of pipes. The return value is a file object, which can be read and written. The default is ‘r’read. The output content can be read by calling the read() or readlines() method of the object. The following is the source code:

def popen (cmd, mode= "r" , buffering= -1 ) :
     if not isinstance(cmd, str):
          raise TypeError( "invalid cmd type (%s, expected string)" % type(cmd))
      if mode not in ( "r" , "w" ):
          raise ValueError( "invalid mode %r" % mode)
      if buffering == 0 or buffering is None :
          raise ValueError( "popen() does not support unbuffered streams")
      import subprocess, io
      if mode == "r" :
         proc = subprocess.Popen(cmd,
                                 shell=True ,
                                 stdout=subprocess.PIPE,
                                 bufsize=buffering)
         return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
      else :
         proc = subprocess.Popen(cmd,
                                 shell=True ,
                                 stdin=subprocess.PIPE,
                                 bufsize=buffering)
         return _wrap_close(io.TextIOWrapper(proc.stdin), proc)

The usage only needs to pass in the necessary parameters and execute it by reading or writing:

os . popen (f 'pyinstaller -F -w D:\program.py' ). read ()

The result of execution is the same as os.system(), and the generated files are in the same directory.

subprocess.run()

The subprocess module is officially used to replace some old module methods. It contains many content methods, which are more complete than os.system() and os.popen(). The subprocess module has multiple methods for calling cmd commands, namely Popen, call, run, and getstatusoutput. Here we only briefly explain the run() method.

The subprocess.run() function executes the specified command, and returns an instance of the CompletedProcess class containing the execution result after the command is executed.

The usage is the same as the os.system() and os.popen() methods, passing in a string command, but the selection of parameters is much more than os.system() and os.popen():

subprocess .run (f 'pyinstaller -F -w D:\program.py' )

This method does not return output by default, only the command and execution status.

Program implementation

We have already known how multiple programs can call the cmd command. This article uses the os.system() method, which is very simple to use. If you require more complexity, you can conduct in-depth research.

The library used to build the GUI is PySimpleGUI:

import  os 
import  PySimpleGUI as sg

If it has not been installed, you can install it with the pip command:

pip  intsall library name

GUI interface design

Because there are no special requirements for functions, it only needs to be able to package multiple programs with only one operation. The final design code is as follows:

# Theme settings
sg.theme( 'LightBrown3' )

# layout settings
layout = [
     [sg.Frame(layout=[
         [
             sg.InputText(key= 'please_select_file' , size=( 24 , 1 ), font=( "Microsoft Yahei" , 10 ), enable_events= True ),
              # FileBrowse can only select a single file FilesBrowse can select multiple files by adding s
             sg.FilesBrowse( 'Get files' , file_types=(( "Text Files" , "*.py" ),), font=( "Microsoft Yahei" , 10 )),
         ],
     ],
         title= 'Select file' , title_color= 'blue' , font=( "Microsoft Yahei" , 10 ), relief=sg.RELIEF_SUNKEN, )],

     [sg.Button( 'Start packaging' , font=( "Microsoft Yahei" , 10 )),
      sg.Text( '' , font=( "Microsoft Yahei" , 10 ), size=( 16 , 0 )), sg.Button( 'Exit program' , font=( "Microsoft Yahei" , 10 ), button_color = ' red' )] # button_color blue red
]

# Create a window
window = sg.Window( 'Package Tool' , layout, font=( "Microsoft Yahei" , 12 ), default_element_size=( 30 , 1 ))

The interface is as follows:

How to use Python to implement a tool for batch packaging programs

widget interface

logical design

The file paths obtained through the interface are separated by ";", which needs to be divided later:

valuelist = []
  # event loop
while True:
      # exit button
     event , values = window.read()
      if event in ( None, 'exit program' ):
          break
     # open file button
     if event == 'please_select_file' :
         fileName = values[ 'please_select_file' ]
          # The obtained file paths are separated by ";" and passed in a list
         valuelist.append(fileName)

     if event == 'start packing' :
          if len( valuelist ) != 0 :
           # pass in the packing function
             pyinstaller_(valuelist)
         else :
             sg.popup( 'File not selected!' )

packing function

The function receives a list, which needs to be read through a loop; the path divided by split will generate a list, which still needs to be read through a loop; the program packaging effect is relatively simple, -F and -w are respectively to generate a single Executable and suppressing the command line window:

def pyinstaller_(valuelist) :
     for i in valuelist:
         a = i.split( ';' )
          for x in a:
             os.system( f'pyinstaller -F -w {x}' )

The final generated .exe executable files are all saved in the dist file:

How to use Python to implement a tool for batch packaging programs

result .exe file

Pros and cons of gadgets:

Advantages: The effect of gadgets is not very useful for people who have other needs, but it is still useful for people who need to package multiple programs. After all, it is necessary to refuse repeated operations.

Disadvantages: The shortcomings of gadgets are obvious. They cannot operate on packaged program icons, and can only execute commands one by one when executing commands, which greatly reduces the efficiency and needs to cooperate with threads and processes.

The content of "How to use Python to implement a tool for batch packaging programs" is introduced here, thank you for reading.


Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+