Methods and steps of C # calling Python script (2 kinds)

Time:2021-5-11

Due to the needs of the project, we need to use the C # console program to execute the python script. After querying all kinds of information, we can successfully call it. Record it for later forgetting.

Only two calling methods are tried. The first one is only applicable to the case that the python script does not contain the third-party module, and the second one is for the case that the python script contains the third-party module. Either way, ironpython needs to be installed first. I use vs2017 tools – nuget Package Manager – manage solution nuget package to search ironpython package installation, or download the installation package from the official website and add a reference after self installation.

Method 1: it is applicable to the case that the python script does not contain the third-party module

C code

using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using System;

namespace CSharpCallPython
{
  class Program
  {
    static void Main(string[] args)
    {
      ScriptEngine pyEngine = Python.CreateEngine();// Creating Python interpreter objects
      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 in the script file
      Console.WriteLine(reStr);

      Console.ReadKey();
    }
  }
}

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)

result

Method 2: it is applicable to the case that the python script contains the third-party module

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";// The path of the python file to be processed is placed in the debug folder in this example
      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"; // Installation path of python2.7
      p.StartInfo.Arguments = sArguments;// Parameters of Python command
      p.StartInfo.UseShellExecute = false;
      p.StartInfo.RedirectStandardOutput = true;
      p.StartInfo.RedirectStandardInput = true;
      p.StartInfo.RedirectStandardError = true;
      p.StartInfo.CreateNoWindow = true;
      p.Start();// Start the process

      Console. Writeline ("finished!");

      Console.ReadKey();
    }
  }
}

Python script


# -*- 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])

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

When calling the python script containing the third-party module, I tried to use the path. Append() method, but there were various problems in debugging, so I gave up and didn’t study it.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]