需求
一开始执行外部的exe的命令被写入xxx.cmd文件中
从python中调用该执行命令
- 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)
注意
一开始写的时候,不知道要反斜杠需要加两个斜杠==\\==而出现无法运行的情况
未解决
output_str为执行返回的结果,但是当有中文输出时,在console端显示为乱码
路径的写法
在windows中,读取文件可以用‘\’,但是在字符串中,’'是被当做转义字符来使用的,所以‘d:\test.txt’会被转成‘d:\a.txt’这是正确路径,所以不会报错。而如果文件中带了\t可能就转义成tab键了。或者\n可能转成换行。
遇到过这样子的错误:
[Error 22] Invalid argument: 'D:\\xxx\\yyy\\zzz\\abc.cmd'
- 使用Linux下的路径写法:
‘d:/test.txt’
创建txt编码
如果直接右击创建文档, 默认的编码方式为ANSI–GBK编码方式,此时输入中文时,在打开txt文件时,需要表明encoding方式,否则会出现"utf-16-le’ codec can’t decode bytes in position 118-119: illegal UTF-16 surrogate"这样子的错误
with open("test.txt", 'w', encoding='utf-8') as f:
或者
with open("test.txt", 'w', encoding='GBK') as f:
打开时使用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)
如果文不存在或者文件错误,此时可以通过except方式返回给用户,或者在UI界面中输出该反馈,提示用户