原理:
项目中把python.exe解释器作为内容同项目一起发布
将py代码作为参数传输给项目包内的python.exe并执行.不需要在本机和安装环境中安装python
--------
如果调用py不需要其他第三方package或对python比较了解 可以下载精简版Windows embeddable package (64-bit)
如果要使用pip安装第三方包,推荐使用winpython包作为解释器 比较完整 可以通过pip命令直接安装扩展包
====
编写一个给C#调用的简单.py作为接口如(同样内置在项目中)
这段代码调用了py第三方项目的一个功能,可通过cmd调用
import sys
import misaki
sys.stdout.reconfigure(encoding='utf-8')
from misaki import zh
if __name__ == "__main__":
text = sys.stdin.read().strip()
g2p = zh.ZHG2P()
ipa = g2p(text)
print(ipa)
#sys.stdout.write(ipa)
通过c#代码调用解释器执行py代码
public static async Task<string> CN2IPA(string text)
{
// 获取当前应用目录
string baseDir = AppDomain.CurrentDomain.BaseDirectory;
string pythonExe = Path.Combine(baseDir, "python", "python.exe");
string scriptPath = Path.Combine(baseDir, "python", "to_phoneme_zh.py");
var psi = new ProcessStartInfo
{
FileName = pythonExe,
Arguments = scriptPath,
//Arguments = $"\"{scriptPath}\" \"{text}\"",
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
StandardInputEncoding = Encoding.UTF8,
};
psi.Environment["PYTHONIOENCODING"] = "utf-8";
//Debug.WriteLine($"py: {pythonExe} script:{scriptPath}");
//Debug.WriteLine($"input: {text}");
using var process = new Process { StartInfo = psi };
process.Start();
process.StandardInput.Write(text);
process.StandardInput.Close();
string result = await process.StandardOutput.ReadToEndAsync();
process.WaitForExit();
return result.Trim();
}
也可先使用.bat批处理命令测试py文件的执行效果.如:
set PATH="C:\Windows\System32";%PATH% chcp 65001 cd /d D:\UWP\文本转语音TTS\KokoroSharp-0.6.2\KokoroSharp\python python.exe to_phoneme_en.py "hello world" pause