C#調(diào)用python腳本的方法詳解
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)文章
C#實(shí)現(xiàn)獲取運(yùn)行平臺(tái)系統(tǒng)信息的方法
這篇文章主要介紹了C#實(shí)現(xiàn)獲取運(yùn)行平臺(tái)系統(tǒng)信息的方法,比較典型的C#應(yīng)用,需要的朋友可以參考下2014-07-07
C#代碼實(shí)現(xiàn)在Excel中為數(shù)據(jù)透視表添加篩選器
數(shù)據(jù)透視表中的篩選功能可幫助用戶根據(jù)特定條件縮小顯示的數(shù)據(jù)范圍,本文將演示如何在?C#?中為?Excel?數(shù)據(jù)透視表添加篩選器,希望對(duì)大家有所幫助2026-05-05
c# 使用WebRequest實(shí)現(xiàn)多文件上傳
這篇文章主要介紹了c# 使用WebRequest實(shí)現(xiàn)多文件上傳的方法,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下2021-03-03
C#傳值方式實(shí)現(xiàn)不同程序窗體間通信實(shí)例
Form2構(gòu)造函數(shù)中接收一個(gè)string類型參數(shù),即Form1中選中行的文本,將Form2的TextBox控件的Text設(shè)置為該string,即完成了Form1向Form2的傳值2013-12-12
c#入門之實(shí)現(xiàn)簡易存款利息計(jì)算器示例
這篇文章主要介紹了c#入門之實(shí)現(xiàn)簡易存款利息計(jì)算器示例,需要的朋友可以參考下2014-04-04

