c#调用python脚本

最开始根据网上大部分人的经验,使用ironPython,但问题太多了,最根本的就是他不支持python3以上的,所以后来使用了进程的方式来调用python文件

var result = string.Empty;
var pypath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"E:main.py");
var p = new ProcessStartInfo();
var sArguments = pypath;
sArguments += " "+param1+" "+param2;//多个参数用空格隔开
//如果没有配置环境变量,就使用python运行程序的绝对路径
p.FileName = @"C:UsersBruceAppDataLocalProgramsPythonPython38-32python.exe";
//p.FileName=@"python.exe"
p.Arguments = sArguments;
p.UseShellExecute = false;
p.RedirectStandardError = true;
p.RedirectStandardOutput = true;
p.CreateNoWindow = true;
using (Process process = Process.Start(p))
{
     using (StreamReader reader = process.StandardOutput)
     {
          string stderr = process.StandardError.ReadToEnd();
          result = reader.ReadToEnd();
     }
}                                    

.py文件代码如下

#!/usr/bin/python
#coding=utf-8
import sys
import xlrd
import xlwt
from xlutils.copy import copy
import clr
clr.AddReference('System.Data')
import pyodbc

def process(dbHost, dbUserName, dbPassword, dbName, templateFileLoc, desFileLoc, userID, startTime, endTime):
    rb = xlrd.open_workbook(templateFileLoc,formatting_info=True)
    wb = copy(rb)
    ws = wb.get_sheet(0)
    connection = pyodbc.connect("DRIVER={SQL Server};SERVER="+dbHost+";DATABASE="+dbName+";UID="+dbUserName+";PWD="+dbPassword+"")
    cursor = connection.cursor() #get this database vernier
    sql = "select * from table"
    cursor.execute(sql) #execute sql statements
    rows = cursor.fetchall() #return a list object
    
    i = 2
    for row in rows: 
        ws.write(i, 0, i-1)
        for j in range(len(row)):
            if type(row[j])==str:
                ws.write(i, j+1, row[j])
        i=i+1
    cursor.close()
    connection.close()
    wb.save(desFileLoc)
    return True
#when you define a method,you must call the function    
process(sys.argv[1], sys.argv[2], sys.argv[3],sys.argv[4],sys.argv[5],sys.argv[6],sys.argv[7],sys.argv[8],sys.argv[9])

最开始是报:no module name ***,这个没有多说的,pip install安装好需要的模块就行了,此处安装clr有个坑,当pip install clr后还是会报错,提示clr没有AddReference属性,因为虽然在程序里是import clr,但是安装的时候要使用pip install ptthonnet。而不能使用pip install clr命令,否则就会安装另外一个名为clr但功能不同的python包

然后就是报:utf-8 codec can’t decode byte 0xbb in position3:invalid start byte,原因是文件里有中文,在python解释器里有中文没关系,但调用python脚本的时候,文件和路径里最好不要有中文

接下来是运行完毕,但实际上并未调用python函数,所以如果是调用脚本里的函数,要么python先执行这个函数,要么在程序里调用这个函数

原文地址:https://www.cnblogs.com/tenfly/p/13522842.html