Skip to content

C#调用python

L edited this page Jul 16, 2019 · 6 revisions

参考资料:
https://codefying.com/2015/10/02/executing-a-python-script-from-a-c-program/

demo:
https://github.com/zLulus/NotePractice/tree/dev3/Console/CSharpUsingPythonDemo

代码

    string progToRun = "test.py";
    char[] spliter = { '\r' };

    Process proc = new Process();
    proc.StartInfo.FileName = "python.exe";
    proc.StartInfo.RedirectStandardOutput = true;
    proc.StartInfo.UseShellExecute = false;
            
    string psw = "123456";
    string parameters2 = "haha";
    //文件路径+参数集合
    proc.StartInfo.Arguments = string.Concat(progToRun, " ", psw.ToString()," ", parameters2.ToString());
    proc.Start();

    StreamReader sReader = proc.StandardOutput;
    string[] output = sReader.ReadToEnd().Split(spliter);

    foreach (string s in output)
        Console.WriteLine(s);

    proc.WaitForExit();

    //取出计算结果
    Console.WriteLine(output[0]);

    Console.Read();
import base64
import hmac
import hashlib
import urllib
import urlparse
import json
import urllib
import sys

def _auth_data():
    psw=sys.argv[1]
    parameters2=sys.argv[2]
    md5 = hashlib.md5()
    md5.update(psw.encode('utf-8'))
    md5.update('hello'.encode('utf-8'))
    s = json.dumps({"assetPwd": md5.hexdigest()})
    r=urllib.quote(s, safe='')
    print r
    return r

if __name__ == '__main__':
    _auth_data()

需要注意的是:
(1)保证已安装任意版本的python,并将其添加到环境变量(或者拷贝python.exe至bin目录根目录)
(2)示例的python版本是2.7,可以用python3,这个和你的环境有关
学习过程中遇到的比较揪心的问题也是“python2找不到python3的库、方法”之类的问题,保证环境一致并且正确啊╮(╯_╰)╭
(3)python基本语法问题,缩进要么是空格,要么是tab,保持一致,否则VS会报错

其他方式

1.InronPython:注意只支持到Python 2.x
C#调用Python脚本并使用Python的第三方模块
2.可以把内容封装成api,发布python的站点,C#通过http调用
即将问题从“C#调用Python”转换为“C#调用Web接口”

Clone this wiki locally