欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#調(diào)用python腳本的方法詳解

 更新時(shí)間:2023年11月10日 10:58:51   作者:thisiszdy  
這篇文章主要為大家詳細(xì)介紹了C#調(diào)用python腳本的方法,文中通過示例代碼介紹的非常詳細(xì),感興趣的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

C#調(diào)用Python腳本方法

class Program
 {
        /// <summary>
        /// 實(shí)時(shí)獲取python輸出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                Console.WriteLine(e.Data);
            }
        }

        static void Main(string[] args)
        {
            Process p = new Process();

            string path = @" .\train.py ";// 獲得python文件的絕對(duì)路徑(將文件放在c#的debug文件夾中可以這樣操作)
            p.StartInfo.FileName = @"python.exe";//沒有配環(huán)境變量的話,寫python.exe的絕對(duì)路徑。如果配了,直接寫"python.exe"即可
            string sArguments = path;
            //foreach (string sigstr in teps)
            //{
            //    sArguments += " " + sigstr;//傳遞參數(shù)
            //}

            //sArguments += " ";

            p.StartInfo.Arguments = sArguments;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            p.ErrorDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);

            try
            {
                p.Start(); //啟動(dòng)程序
                p.BeginOutputReadLine();
                p.BeginErrorReadLine();
                p.WaitForExit(); //等待程序執(zhí)行完退出進(jìn)程
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + e.StackTrace);
            }

			//關(guān)閉進(jìn)程
            p.Kill();
            p.Close();
        }
    }

Python端

1、Python報(bào)ImportError: No module named 'xxx’錯(cuò)誤

解決方案:

import sys  
sys.path.append('需要引用模塊的地址')

# sys.path.append("..")   # 這代表添加當(dāng)前路徑的上一級(jí)目錄

2、Python沒有進(jìn)行實(shí)時(shí)輸出結(jié)果

原因:一般會(huì)先將字符送到緩沖區(qū),然后再打印。但由于緩沖區(qū)沒滿,不會(huì)打印。就需要采取一些手段。如每次打印后強(qiáng)行刷新緩沖區(qū)。

解決方案:在Print函數(shù)后面增加sys.stdout.flush()

方法補(bǔ)充

除了上文的方法,小編還為大家整理了C#調(diào)用Python腳本的其他方法,希望對(duì)大家有所幫助

方式一:適用于python腳本中不包含第三方模塊的情況

C#代碼

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;
 
namespace CSharpCallPython
{
  class Program
  {
    static void Main(string[] args)
    {
      ScriptEngine pyEngine = Python.CreateEngine();//創(chuàng)建Python解釋器對(duì)象
      dynamic py = pyEngine.ExecuteFile(@"test.py");//讀取腳本文件
      int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 };
      string reStr = py.main(array);//調(diào)用腳本文件中對(duì)應(yīng)的函數(shù)
      Console.WriteLine(reStr);
 
      Console.ReadKey();
    }
  }
}

Python代碼

def main(arr):
  try:
    arr = set(arr)
    arr = sorted(arr)
    arr = arr[0:]
    return str(arr)
  except Exception as err:
    return str(err)
 

方式二:適用于python腳本中包含第三方模塊的情況

C#代碼 

using System;
using System.Collections;
using System.Diagnostics;
namespace Test
{
  class Program
  {
    static void Main(string[] args)
    {
      Process p = new Process();
      string path = "reset_ipc.py";//待處理python文件的路徑,本例中放在debug文件夾下
      string sArguments = path;
      ArrayList arrayList = new ArrayList();
      arrayList.Add("com4");
      arrayList.Add(57600);
      arrayList.Add("password");
      foreach (var param in arrayList)//添加參數(shù)
      {
        sArguments += " " + sigstr;
      }
      p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安裝路徑
      p.StartInfo.Arguments = sArguments;//python命令的參數(shù)
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.RedirectStandardInput = true;
      p.StartInfo.RedirectStandardError = true;
      p.StartInfo.CreateNoWindow = true;
      p.Start();//啟動(dòng)進(jìn)程
      Console.WriteLine("執(zhí)行完畢!");
      Console.ReadKey();
    }
  }
}

python腳本

# -*- coding: UTF-8 -*-
import serial
import time
def resetIPC(com, baudrate, password, timeout=0.5):
  ser=serial.Serial(com, baudrate, timeout=timeout)
  flag=True
  try:
    ser.close()
    ser.open()
    ser.write("\n".encode("utf-8"))
    time.sleep(1)
    ser.write("root\n".encode("utf-8"))
    time.sleep(1)
    passwordStr="%s\n" % password
    ser.write(passwordStr.encode("utf-8"))
    time.sleep(1)
    ser.write("killall -9 xxx\n".encode("utf-8"))
    time.sleep(1)
    ser.write("rm /etc/xxx/xxx_user.*\n".encode("utf-8"))
    time.sleep(1)
    ser.write("reboot\n".encode("utf-8"))
    time.sleep(1)
  except Exception:
    flag=False
  finally:
    ser.close()
  return flag
resetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

到此這篇關(guān)于C#調(diào)用python腳本的方法詳解的文章就介紹到這了,更多相關(guān)C#調(diào)用python腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論