C# calls Python script method
class Program { /// <summary> /// Get python output in real time /// </summary> /// <param name="sender"></param> /// <param name="e"></param> static void p_OutputDataReceived(object sender, DataReceivedEventArgs e) { if (!()) { (); } } static void Main(string[] args) { Process p = new Process(); string path = @" .\ ";// Get the absolute path to the python file (put the file in cThis is how to operate in the # debug folder) = @"";//If there is no environment variable, the absolute path to be written. If it matches, just write "" string sArguments = path; //foreach (string sigstr in teps) //{ // sArguments += " " + sigstr;//Pass parameters //} //sArguments += " "; = sArguments; = false; = true; = true; = true; = true; += new DataReceivedEventHandler(p_OutputDataReceived); += new DataReceivedEventHandler(p_OutputDataReceived); try { (); //Start the program (); (); (); //Waiting for the program to be executed and exiting the process } catch (Exception e) { ( + ); } //Close the process (); (); } }
Python side
1. Python reports ImportError: No module named 'xxx' error
Solution:
import sys ('Requiring the address of the module') # ("..") # This represents the previous directory where the current path is added
2. Python does not output real-time results
Reason: Generally, characters are sent to the buffer first and then printed. However, since the buffer is not full, it will not print. Some measures are needed. For example, after each printing, the buffer is forced to refresh.
Solution: Add() after Print function
Method supplement
Method 1: Applicable to cases where python scripts do not contain third-party modules
C# code
using ; using ; using System; namespace CSharpCallPython { class Program { static void Main(string[] args) { ScriptEngine pyEngine = ();//Create Python interpreter object dynamic py = (@"");//Read the script file int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 }; string reStr = (array);//Calling the corresponding function in the script file (reStr); (); } } }
Python code
def main(arr): try: arr = set(arr) arr = sorted(arr) arr = arr[0:] return str(arr) except Exception as err: return str(err)
Method 2: Applicable to cases where third-party modules are included in python scripts
C# code
using System; using ; using ; namespace Test { class Program { static void Main(string[] args) { Process p = new Process(); string path = "reset_ipc.py";//The path of the pending python file, in this example, is placed in the debug folder string sArguments = path; ArrayList arrayList = new ArrayList(); ("com4"); (57600); ("password"); foreach (var param in arrayList)//Add parameters { sArguments += " " + sigstr; } = @"D:\Python2\"; //The installation path of python2.7 = sArguments;//Parses of python command = false; = true; = true; = true; = true; ();//Start the process ("Execution is complete!"); (); } } }
python script
# -*- coding: UTF-8 -*- import serial import time def resetIPC(com, baudrate, password, timeout=0.5): ser=(com, baudrate, timeout=timeout) flag=True try: () () ("\n".encode("utf-8")) (1) ("root\n".encode("utf-8")) (1) passwordStr="%s\n" % password (("utf-8")) (1) ("killall -9 xxx\n".encode("utf-8")) (1) ("rm /etc/xxx/xxx_user.*\n".encode("utf-8")) (1) ("reboot\n".encode("utf-8")) (1) except Exception: flag=False finally: () return flag resetIPC([1], [2], [3])
This is the end of this article about the detailed explanation of the method of calling python scripts in C#. For more related content of calling python scripts in C#, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!