当前位置:   article > 正文

C#调用python脚本的方法步骤

c#调用python脚本

方式一:适用于python脚本中不包含第三方模块的情况

C#代码

  1. using IronPython.Hosting;
  2. using Microsoft.Scripting.Hosting;
  3. using System;
  4. namespace CSharpCallPython
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. ScriptEngine pyEngine = Python.CreateEngine();//创建Python解释器对象
  11. dynamic py = pyEngine.ExecuteFile(@"test.py");//读取脚本文件
  12. int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
  13. string reStr = py.main(array);//调用脚本文件中对应的函数
  14. Console.WriteLine(reStr);
  15. Console.ReadKey();
  16. }
  17. }
  18. }

Python代码

  1. def main(arr):
  2. try:
  3. arr = set(arr)
  4. arr = sorted(arr)
  5. arr = arr[0:]
  6. return str(arr)
  7. except Exception as err:
  8. return str(err)

方式二:适用于python脚本中包含第三方模块的情况

C#代码 

  1. using System;
  2. using System.Collections;
  3. using System.Diagnostics;
  4. namespace Test
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. Process p = new Process();
  11. string path = "reset_ipc.py";//待处理python文件的路径,本例中放在debug文件夹下
  12. string sArguments = path;
  13. ArrayList arrayList = new ArrayList();
  14. arrayList.Add("com4");
  15. arrayList.Add(57600);
  16. arrayList.Add("password");
  17. foreach (var param in arrayList)//添加参数
  18. {
  19. sArguments += " " + sigstr;
  20. }
  21. p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径
  22. p.StartInfo.Arguments = sArguments;//python命令的参数
  23. p.StartInfo.UseShellExecute = false;
  24. p.StartInfo.RedirectStandardOutput = true;
  25. p.StartInfo.RedirectStandardInput = true;
  26. p.StartInfo.RedirectStandardError = true;
  27. p.StartInfo.CreateNoWindow = true;
  28. p.Start();//启动进程
  29. Console.WriteLine("执行完毕!");
  30. Console.ReadKey();
  31. }
  32. }
  33. }

python脚本

  1. # -*- coding: UTF-8 -*-
  2. import serial
  3. import time
  4. def resetIPC(com, baudrate, password, timeout=0.5):
  5. ser=serial.Serial(com, baudrate, timeout=timeout)
  6. flag=True
  7. try:
  8. ser.close()
  9. ser.open()
  10. ser.write("\n".encode("utf-8"))
  11. time.sleep(1)
  12. ser.write("root\n".encode("utf-8"))
  13. time.sleep(1)
  14. passwordStr="%s\n" % password
  15. ser.write(passwordStr.encode("utf-8"))
  16. time.sleep(1)
  17. ser.write("killall -9 xxx\n".encode("utf-8"))
  18. time.sleep(1)
  19. ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
  20. time.sleep(1)
  21. ser.write("reboot\n".encode("utf-8"))
  22. time.sleep(1)
  23. except Exception:
  24. flag=False
  25. finally:
  26. ser.close()
  27. return flag
  28. resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

调用包含第三方模块的python脚本时,需要在Python安装目录且包含第三方模块文件夹;打包时可以拷贝该文件到程序运行目录,直接打包进去

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/478505
推荐阅读
相关标签
  

闽ICP备14008679号