2024年1月28日发(作者:)
C#调用Python中Pyd第三方库方法]
一 、目标:
通过C#使用命令行的方式调用Python中含有pyd第三方库的脚步程序(注:通过IronPython相关DLL文件的方式调用Pyd格式的库文件非常不方便)
二、所需软件以及环境配置
1 软件:python3.5.1,VS2010,Pyd文件
2 环境配置:添加python路径到环境变量Path中,如下图所示:
C:UsersAdministratorAppDataLocalProgramsPythonPython35Lib;
C:UsersAdministratorAppDataLocalProgramsPythonPython35;
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:WindowsSysWOW64下。配置完成
三、C#调用python脚本
1 首先通过VS建立一个C#的控制台
2 所需要的using List如下:
using System;
using c;
using ;
using ;
using g;
using g;
using stics;
3 执行脚本
class Program
{
private static void CallExe()
{
Process usepy = new Process();
string path = "F:";
ProcessStartInfo startInfo = new ProcessStartInfo(@"",
"F:");
llExecute = false;
NoWindow = false;
nfo = 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 (ns(" "))
{
return """ + input + """;
}
return input;
}
private static void CallExe()
{
Process usepy = new Process();
string pythonPath =
e(rectory, "");
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);
ine(arg);
ProcessStartInfo startInfo = new ProcessStartInfo(@"", arg);
llExecute = false;
NoWindow = false;
nfo = startInfo;
// nts = path;
// llExecute = false;
// ctStandardOutput = true;
// ctStandardInput = true;
// ctStandardError = true;
// NoWindow = false;
// DataReceived += (sender, args) => ine("received
output: {0}", );
();
// utputReadLine();
ne();
}
static void Main(string[] args)
{
CallExe();
}
}
}
本文发布于:2024-01-28 22:57:31,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170645385210897.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |