C#調(diào)用python腳本的方法詳解
C#調(diào)用Python腳本方法
class Program
{
/// <summary>
/// 實時獲取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文件的絕對路徑(將文件放在c#的debug文件夾中可以這樣操作)
p.StartInfo.FileName = @"python.exe";//沒有配環(huán)境變量的話,寫python.exe的絕對路徑。如果配了,直接寫"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(); //啟動程序
p.BeginOutputReadLine();
p.BeginErrorReadLine();
p.WaitForExit(); //等待程序執(zhí)行完退出進程
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
}
//關(guān)閉進程
p.Kill();
p.Close();
}
}
Python端
1、Python報ImportError: No module named 'xxx’錯誤
解決方案:
import sys
sys.path.append('需要引用模塊的地址')
# sys.path.append("..") # 這代表添加當前路徑的上一級目錄
2、Python沒有進行實時輸出結(jié)果
原因:一般會先將字符送到緩沖區(qū),然后再打印。但由于緩沖區(qū)沒滿,不會打印。就需要采取一些手段。如每次打印后強行刷新緩沖區(qū)。
解決方案:在Print函數(shù)后面增加sys.stdout.flush()
方法補充
除了上文的方法,小編還為大家整理了C#調(diào)用Python腳本的其他方法,希望對大家有所幫助
方式一:適用于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解釋器對象
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)用腳本文件中對應的函數(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();//啟動進程
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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#代碼實現(xiàn)在Excel中為數(shù)據(jù)透視表添加篩選器
數(shù)據(jù)透視表中的篩選功能可幫助用戶根據(jù)特定條件縮小顯示的數(shù)據(jù)范圍,本文將演示如何在?C#?中為?Excel?數(shù)據(jù)透視表添加篩選器,希望對大家有所幫助2026-05-05

