参考资料:
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版本是2.7,可以用python3,这个和你的环境有关
学习过程中遇到的比较揪心的问题也是“python2找不到python3的库、方法”之类的问题,保证环境一致并且正确啊╮(╯_╰)╭
(2)python基本语法问题,缩进要么是空格,要么是tab,保持一致,否则VS会报错