C# 调用 python3

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”了

转载于:https://www.cnblogs.com/lantingg/p/9418307.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值