SoFunction
Updated on 2025-04-10

How to call an external exe program in python

need

The command to execute external exe is written to the file at the beginning

Call this execution command from python

  • import os
  • popen
import os

def run_GenrateTexts(file_name):
    cmd = '.\\tool\\TranslationDir\\ '
    cmd = cmd + file_name + ' . 60'
    print(cmd)
    res = (cmd)
    output_str = ()
    print(output_str)

Notice

When I first wrote, I didn't know that I needed to add two slashes ==\\== and it would not work.

Not resolved

output_str is the result returned by the execution, but when there is Chinese output, it is displayed as garbled on the console side.

How to write a path

In Windows, you can use ‘\’ to read files, but in a string, ‘' is used as an escape character, so ‘d:\’ will be converted to ‘d:\’. This is the correct path, so there will be no error.

And if the file contains \t, it may be escaped into the tab key. Or \nMay be converted to a newline.

Have encountered such an error

[Error 22] Invalid argument: 'D:\\xxx\\yyy\\zzz\\'  

Use the path writing method under Linux:

‘d:/'

Create txt encoding

If you right-click to create a document, the default encoding method is ANSI-GBK encoding method. When entering Chinese, when opening the txt file, you need to indicate the encoding method, otherwise it will appear.

"utf-16-le’ codec can’t decode bytes in position 118-119: illegal UTF-16 surrogate"

Such a mistake

 with open("", 'w', encoding='utf-8') as f:

or

 with open("", 'w', encoding='GBK') as f:

Use try and except when opening

def my_file_open(file_path):
    try:
        f = open(file_path, 'r', encoding='utf-8')
        convert_cmd = ()
        print(convert_cmd)
        ()
    except Exception as e:
        print(e)

If the text does not exist or the file is incorrect, you can return it to the user through except, or output the feedback in the UI interface to prompt the user to

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.