C#调用python脚本的方法详解
作者:thisiszdy
这篇文章主要为大家详细介绍了C#调用python脚本的方法,文中通过示例代码介绍的非常详细,感兴趣的朋友们下面随着小编来一起学习学习吧
C#调用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";//没有配环境变量的话,写python.exe的绝对路径。如果配了,直接写"python.exe"即可
string sArguments = path;
//foreach (string sigstr in teps)
//{
// sArguments += " " + sigstr;//传递参数
//}
//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(); //等待程序执行完退出进程
}
catch (Exception e)
{
Console.WriteLine(e.Message + e.StackTrace);
}
//关闭进程
p.Kill();
p.Close();
}
}
Python端
1、Python报ImportError: No module named 'xxx’错误
解决方案:
import sys
sys.path.append('需要引用模块的地址')
# sys.path.append("..") # 这代表添加当前路径的上一级目录
2、Python没有进行实时输出结果
原因:一般会先将字符送到缓冲区,然后再打印。但由于缓冲区没满,不会打印。就需要采取一些手段。如每次打印后强行刷新缓冲区。
解决方案:在Print函数后面增加sys.stdout.flush()
方法补充
除了上文的方法,小编还为大家整理了C#调用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();//创建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);//调用脚本文件中对应的函数
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)//添加参数
{
sArguments += " " + sigstr;
}
p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7的安装路径
p.StartInfo.Arguments = sArguments;//python命令的参数
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();//启动进程
Console.WriteLine("执行完毕!");
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])到此这篇关于C#调用python脚本的方法详解的文章就介绍到这了,更多相关C#调用python脚本内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
