c# python3_C#编程之C# 调用 python3

本文主要向大家介绍了C#编程之C# 调用 python3,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

1.C# 调用python

本质上是使用命令行运行python

1.1 C# 使用命令行

program.cs

using System;

using System.Diagnostics;

using System.IO;

namespace test

{

class Program

{

static void Main(string[] args)

{

Program p = new Program();

string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");

Console.WriteLine(result);

Console.ReadKey();

}

public string run_cmd(string program, string cmd)

{

ProcessStartInfo start = new ProcessStartInfo();

start.FileName = program;

start.Arguments = cmd;

start.UseShellExecute = false;          // Do not use OS shell

start.CreateNoWindow = true;            // We don‘t need new window

start.RedirectStandardOutput = true;    // Any output, generated by application will be redirected back

start.RedirectStandardError = true;     // Any error in standard output will be redirected back (for example exceptions)

using (Process process = Process.Start(start))

{

using (StreamReader reader = process.StandardOutput)

{

string result = process.StandardError.ReadToEnd();

if (result == null || result == "")

{

result = reader.ReadToEnd();

}

return result;

}

}

}

}

}

代码运行结果

调用run_cmd相当于执行了cmd命令,所以就有了使用命令行运行python脚本的方式

1.2. C# 调用 python3脚本

假设C盘根目录下有如下脚本 test1.py

import sys

def add(a,b):

return a+b

if __name__ == "__main__":

print(sys.argv[1])

print("hello python")

在 program.cs 中加入函数runPython,并修改main函数

static void Main(string[] args)

{

Program p = new Program();

//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");

string result = p.runPython("C:\\test1.py", "\"Form C#:\"");

Console.WriteLine(result);

Console.ReadKey();

}

public string runPython(string filename, string cmd)

{

string cmd1 = string.Format("{0} {1}", filename, cmd);

return run_cmd("python.exe", cmd1);

}

代码运行结果

1.3 C# 调用python3内的函数

我们知道使用python -c可以直接执行python代码,所以合理构造语句就可以直接调用python脚本内的函数了:python -c "print(‘hello python‘)"。

若要调用脚本里的函数,常规写法为:

import sys

sys.path.append(‘c:\\‘)

import test1

print(test1.add(3,4))

缩成一行就是python -c "import sys;sys.path.append(‘c:\\‘);import test1;print(test1.add(3,4))"

在 program.cs 中加入函数runPyFunc,并修改main函数

static void Main(string[] args)

{

Program p = new Program();

//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");

//string result = p.runPython("C:\\test.py", "\"Form C#:\"");

string result = p.runPyFunc(@"C:\\","test1","add","3,4");

Console.WriteLine(result);

Console.ReadKey();

}

public string runPyFunc(string path, string filename, string functionname, string parameter)

{

string cmd = string.Format("-c \"import sys;sys.path.append(‘{0}‘);import {1};print({1}.{2}({3}))\"", path, filename, functionname, parameter);

return run_cmd("python.exe", cmd);

}

运行就可以得到结果“7”了

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 调用 C# dll 库最简方法有以下两种: 1.使用Pythonnet库:Pythonnet是一个能够把 Python 和 .NET 程序集融合在一起的库,可以很方便地调用 C# dll 库。首先需要安装Pythonnet库,在Python中导入clr模块,然后使用clr.AddReference添加dll库的引用,最后就可以使用C# dll中的类和函数了。 示例代码: ```python import clr clr.AddReference("test.dll") # 添加dll引用 from test import Test # 导入C#类Test if __name__ == '__main__': t = Test() print(t.HelloWorld()) # 调用C#类Test中的HelloWorld方法 ``` 2.使用ctypes库:ctypes是Python的标准库之一,也可以用来调用C# dll库。可以使用LoadLibrary函数加载dll库,然后使用dll中的函数和类。 示例代码: ```python import ctypes # 加载dll库 test_dll = ctypes.WinDLL("test.dll") # 定义C#类Test中的HelloWorld函数 test_dll.Test_HelloWorld.restype = ctypes.c_char_p test_dll.Test_HelloWorld.argtypes = [] if __name__ == '__main__': print(test_dll.Test_HelloWorld().decode()) # 调用C# dll中的函数Test_HelloWorld ``` 需要注意的是,使用ctypes库调用C# dll库需要在C#中使用__declspec(dllexport)标记暴露函数和类,例如: ```csharp using System; using System.Runtime.InteropServices; namespace Test { public class Test { [DllImport("test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr Test_HelloWorld(); public string HelloWorld() { return Marshal.PtrToStringUni(Test_HelloWorld()); } } } ``` 以上就是Python 调用 C# dll 库最简方法的详细介绍。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值