C# 调用python程序并读取python代码的运行结果

2 篇文章 0 订阅

C# 调用python程序并读取python代码的运行结果

问题背景

在C#的学习过程中,需要通过C#的程序调用python的程序并通过C#读取python程序运行的结果。

解决方法

在C#中需要通过下面的代码 调用python的解释器 和 python的程序文件,并通过C#代码传递给python程序并执行python程序打印结果。

C#程序

string pythonfilepath = @"D:\pythonCode\python\color.py ";
string pythonpath = @"C:\Programs\Python\Python37\python.exe";//python解释器
string fileabsolutename = @"D:\图片\20220331-102820-220.JPG";
string strArgument = pythonfilepath + fileabsolutename;
ProcessStartInfo startPythonInfo = new ProcessStartInfo(pythonpath, strArgument);
startPythonInfo.UseShellExecute = false;  // 是否使用操作系统的shell启动进程
startPythonInfo.RedirectStandardOutput = true;  // 是否将应用程序的输出写入到Process.StandardOutput流中。
startPythonInfo.RedirectStandardError = true;  // 是否将应用程序的错误输出写入到Process.StandardError流中。
startPythonInfo.RedirectStandardInput = true;
startPythonInfo.CreateNoWindow = true;

Process process = new Process();
process.StartInfo = startPythonInfo;

process.Start();
string output = process.StandardOutput.ReadToEnd();//output即为python程序运行的结果
Console.WriteLine("结果:" + output);

process.BeginErrorReadLine();
process.WaitForExit();

需要注意的时候上面的路径参数pythonfilepath、pythonpath和fileabsolutename中不要有空格,否则下面的python代码在解析参数时会出现错误。

python代码

python程序文件中的代码如下所示

import sys

def image_func(path):
    return "hello world"


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    a = image_func(sys.argv[1])
    print(a)

其中sys.argv[1]的值是C#代码中的fileabsolutename的值,

这样的话,C#中读取的output的值就是python代码中print的值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值