C#调用Python中Pyd第三方库方法] 一 、目标:
通过C#使用命令行的方式调用Python中含有pyd第三方库的脚步程序(注:通过IronPython相关DLL文件的方式调用Pyd格式的库文件非常不方便) 二、所需软件以及环境配置
1 软件:python3.5.1,VS2010,Pyd文件
2 环境配置:添加python路径到环境变量Path中,如下图所示: C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\Lib; C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35;
3 Pyd文件配置
将Pyd文件放到python根目录的Lib文件中(若为执行该操作会在导入python模块时出现No module named XXX),如下所示:
图2 找到一个Pyd文件
图3 将Pyd放到指定的路径下
4 与Pyd相关的DLL文件配置
为了使Pyd包能正常导入,需要将与之相关的DLL文件放到windows 系统目录下,如下图所示:
图5 与文中Pyd文件对应的DLL文件
将图5中的DLL文件放到C:\\Windows\\SysWOW下。配置完成 三、C#调用python脚本
1 首先通过VS建立一个C#的控制台 2 所需要的using List如下:
using System;
using System.Collections.Generic; using System.Linq; using System.Text;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System.Diagnostics;
3 执行脚本
class Program {
private static void CallExe() {
Process usepy = new Process(); string path = \"F:\\\\cloud.py\";
ProcessStartInfo startInfo = new ProcessStartInfo(@\"python.exe\", \"F:\\\\cloud.py\");
startInfo.UseShellExecute = false; startInfo.CreateNoWindow = false;
usepy.StartInfo = startInfo;
}
}
程序中path为所要执行的指定路径下面的python脚本名,文中脚本执行效果如下:
图6 通过C#调用python脚本执行效果
4 路径中有空格字符处理
4.1问题描述:再用命令行运行python的相关程序时,尤其是当输入python中的变量有路径或者其他字符行数组时,不能直接在变量中输入“空格”字符,否则python无法识别
解决方法:在python脚本路径中前后加入“\\”,如下程序所示:\"\\\"\" +
input + \"\\\"\";input 为输入的路径
namespace CloudService {
class Program {
private static string getValidArgument(string input) {
if (input.Contains(\" \")) {
return \"\\\"\" + input + \"\\\"\"; }
return input; }
private static void CallExe() {
Process usepy = new Process(); string pythonPath =
System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"cloud.py\"); string imagePath = @\"C:/CC_SDK_DATA/data/Lion fountain/Photos\"; string projectPath = @\"C:/CC_SDK_DATA/projectPy/automaster\"; string arg = getValidArgument(pythonPath) + \" \" +
getValidArgument(imagePath) + \" \" + getValidArgument(projectPath); Console.WriteLine(arg);
ProcessStartInfo startInfo = new ProcessStartInfo(@\"python.exe\", arg); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = false;
usepy.StartInfo = startInfo;
// usepy.StartInfo.Arguments = path;
// usepy.StartInfo.UseShellExecute = false;
// usepy.StartInfo.RedirectStandardOutput = true; // usepy.StartInfo.RedirectStandardInput = true; // usepy.StartInfo.RedirectStandardError = true; // usepy.StartInfo.CreateNoWindow = false;
// usepy.OutputDataReceived += (sender, args) => Console.WriteLine(\"received output: {0}\ usepy.Start();
// usepy.BeginOutputReadLine(); Console.ReadLine(); }
static void Main(string[] args) {
CallExe(); } } }