Get the App
SLTechnology News&Howtos  ›  Development  › 

What are the steps for C # to call a python script?

Shulou Source: shulou.com Published: 2022-06-02 21:27:53 09月26日 Update

In this issue, Xiaobian will bring you about the method steps of C#calling python scripts. The article is rich in content and analyzed and described from a professional perspective. After reading this article, I hope you can gain something.

Due to project needs, need to use C#console program to execute python script, query a variety of information can be successfully called, record it, in case later forgotten.

Only two invocation methods were tried, the first only for cases where Python scripts do not contain third-party modules, and the second for cases where Python scripts contain third-party modules. Either way, IronPython needs to be installed first. I am through vs2017 tools->NuGet package manager-> NuGet package management solutions, search for IronPython package installation, you can also download the installation package on the official website and add references after installing it.

Method 1: Applicable to Python scripts that do not contain third-party modules

C#code

using IronPython.Hosting; using Microsoft.Scripting.Hosting; using System; namespace CSharpCallPython{ class Program { static void Main(string[] args) { ScriptEngine pyEngine = Python.CreateEngine();//Create Python interpreter object dynamic py = pyEngine.ExecuteFile(@"test.py");//Read script file int[] array = new int[9] { 9, 3, 5, 7, 2, 1, 3, 6, 8 }; string reStr = py.main(array);//Call the corresponding function Console.WriteLine(reStr); Console.ReadKey(); } }} in the script file

Python script

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

results

Method 2: Applicable to Python scripts containing third-party modules

C#code

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";//path to python file to be processed, in this case under debug folder string sArguments = path; ArrayList arrayList = new ArrayList(); arrayList.Add("com4"); arrayList.Add(57600); arrayList.Add ("password"); foreach (var param in arrayList)//Add parameters { sArguments += " " + sigstr; } p.StartInfo.FileName = @"D:\Python2\python.exe"; //python2.7 installation path p.StartInfo.Arguments = sArguments;//python command parameters p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start();//Start process Console.WriteLine("Execution complete! "); Console.ReadKey(); } }}

Python script

# -*- coding: UTF-8 -*-import serialimport timedef 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 flagresetIPC(sys.argv[1], sys.argv[2], sys.argv[3])

The python script above is implemented to restart the IPC device, and the test function is successful.

When calling python scripts containing third-party modules, I tried to use path. append() mode, debugging had various problems, and finally gave up, no research.

The above is what the method steps of C#calling python script shared by Xiaobian are. If there is a similar doubt, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.

Tags: Script utf-8 C# mode module third party situation file method step success code content parameter path package analysis attempt management medium and small Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL Microsoft macOS MariaDB OPPO Reno