欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python如何調(diào)用外部的exe程序

 更新時(shí)間:2025年02月05日 09:22:02   作者:wjjontheway  
本文介紹了在Python中執(zhí)行外部exe命令時(shí)遇到的問(wèn)題及解決方法,包括路徑寫(xiě)法、中文輸出亂碼以及文件編碼等問(wèn)題,并提供了一些個(gè)人經(jīng)驗(yàn)

需求

一開(kāi)始執(zhí)行外部的exe的命令被寫(xiě)入xxx.cmd文件中

從python中調(diào)用該執(zhí)行命令

  • import os
  • popen
import os

def run_GenrateTexts(file_name):
    cmd = '.\\tool\\TranslationDir\\TranslationConsole.exe '
    cmd = cmd + file_name + ' . 60'
    print(cmd)
    res = os.popen(cmd)
    output_str = res.read()
    print(output_str)

注意

一開(kāi)始寫(xiě)的時(shí)候,不知道要反斜杠需要加兩個(gè)斜杠==\\==而出現(xiàn)無(wú)法運(yùn)行的情況

未解決

output_str為執(zhí)行返回的結(jié)果,但是當(dāng)有中文輸出時(shí),在console端顯示為亂碼

路徑的寫(xiě)法

在windows中,讀取文件可以用‘\’,但是在字符串中,’'是被當(dāng)做轉(zhuǎn)義字符來(lái)使用的,所以‘d:\test.txt’會(huì)被轉(zhuǎn)成‘d:\a.txt’這是正確路徑,所以不會(huì)報(bào)錯(cuò)。

而如果文件中帶了\t可能就轉(zhuǎn)義成tab鍵了?;蛘運(yùn)n可能轉(zhuǎn)成換行。

遇到過(guò)這樣子的錯(cuò)誤

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

使用Linux下的路徑寫(xiě)法:

‘d:/test.txt'

創(chuàng)建txt編碼

如果直接右擊創(chuàng)建文檔, 默認(rèn)的編碼方式為ANSI–GBK編碼方式,此時(shí)輸入中文時(shí),在打開(kāi)txt文件時(shí),需要表明encoding方式,否則會(huì)出現(xiàn)

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

這樣子的錯(cuò)誤

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

或者

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

打開(kāi)時(shí)使用try和except

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

如果文不存在或者文件錯(cuò)誤,此時(shí)可以通過(guò)except方式返回給用戶,或者在UI界面中輸出該反饋,提示用戶

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論