前言
工作中需要做一些较复杂的数据处理工作,编码语言是C#,通过调研发现无合适的第三方库直接调用来做相应处理,而拥有强大第三方库的python语言可以很好的完成这项任务,故有次文记录使用C#调用python脚本的方法步骤。
一、调用的脚本
将处理数据的方法编写为py脚本,下面代码为说明情况,以简单的加法运算作以说明。
import sys
import numpy as np
# 两个整数相加
def add_fun(a, b):
return np.add(a, b)
if __name__ == '__main__':
result = add_fun(int(sys.argv[1]), int(sys.argv[2]))
print(result)
说明:调用py脚本的入口为main函数,通过解析调用py脚本的命令行参数,输入到处理方法中作相应处理后返回结果,需要使用print打印结果。
二、调用方法
为了测试,单独建立了一个控制台应用程序项目用于测试方法的有效性。
using System;
using System.Diagnostics;
namespace MyConsoleAppTest
{
class Program
{
static void Main(string[] args)
{
Process p = new Process()
// 启用的python解释器绝对位置
p.StartInfo.FileName = @"D:\..\..\python.exe"
// 调用py脚本命令行参数
p.StartInfo.Arguments = " " + @"E:\..\..\python_script.py" + "12" + " " + "34";
// 隐藏控制台窗口
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
// 重定向输入、输出和错误流
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
// 启动进程
p.Start();
p.WaitForExit(); // 等待进程结束
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
}
}
}
说明:调用py脚本命令行参数,如果输入参数数据量较大,建议以为文件的形式(比如json)进行保存和读取,否则,可以直接以字符串的形式作为输入参数。
通过运行控制台应用程序,vs调试控制台输出“46”,表明该应用程序调用py脚本成功。