수색…


소개

이 문서는 C #과 Python 스크립트 간의 프로세스 간 통신의 샘플 구현을 제공합니다.

비고

위의 예제에서 데이터는 NuGet 관리자를 통해 설치할 수있는 MongoDB.Bson 라이브러리를 사용하여 일련 번호가 매겨집니다 .

그렇지 않으면 원하는 JSON 직렬화 라이브러리를 사용할 수 있습니다.


다음은 프로세스 간 의사 소통 구현 단계입니다.

  • 입력 인수는 JSON 문자열로 직렬화되어 임시 텍스트 파일에 저장됩니다.

     BsonDocument argsBson = BsonDocument.Parse("{ 'x' : '1', 'y' : '2' }"); 
     string argsFile = string.Format("{0}\\{1}.txt", Path.GetDirectoryName(pyScriptPath), Guid.NewGuid());
    
  • Python 인터프리터 python.exe는 임시 텍스트 파일에서 JSON 문자열을 읽고 입력 인수를 취소하는 python 스크립트를 실행합니다.

     filename = sys.argv[ 1 ]
     with open( filename ) as data_file:  
        input_args = json.loads( data_file.read() )
    
     x, y = [ float(input_args.get( key )) for key in [ 'x', 'y' ] ]
    
  • Python 스크립트가 실행되고 출력 딕셔너리가 JSON 문자열로 직렬화되고 명령 창에 인쇄됩니다.

     print json.dumps( { 'sum' : x + y , 'subtract' : x - y } )
    

    여기에 이미지 설명을 입력하십시오.

  • C # 응용 프로그램에서 출력 JSON 문자열을 읽습니다.

     using (StreamReader myStreamReader = process.StandardOutput)
     {
        outputString = myStreamReader.ReadLine();
        process.WaitForExit();
     }
    

여기에 이미지 설명을 입력하십시오.

C #과 Python 스크립트 사이의 프로세스 간 통신을 사용하여 Excel 스프레드 시트에서 직접 Python 스크립트를 호출 할 수있는 프로젝트에 있습니다.

이 프로젝트는 C # 용 ExcelDNA 추가 기능 - Excel 바인딩을 사용합니다.

소스 코드는 GitHub 저장소에 저장 됩니다.

다음은 프로젝트의 개요를 제공하고 4 단계로 시작하는 데 도움이되는 위키 페이지에 대한 링크입니다.

예제와 프로젝트가 유용하다는 사실을 알기를 바랍니다.


C # 응용 프로그램에서 호출 할 파이썬 스크립트

import sys
import json

# load input arguments from the text file
filename = sys.argv[ 1 ]
with open( filename ) as data_file:   
    input_args = json.loads( data_file.read() )

# cast strings to floats
x, y = [ float(input_args.get( key )) for key in [ 'x', 'y' ] ]

print json.dumps( { 'sum' : x + y , 'subtract' : x - y } )

파이썬 스크립트를 호출하는 C # 코드

using MongoDB.Bson;
using System;
using System.Diagnostics;
using System.IO;

namespace python_csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // full path to .py file
            string pyScriptPath = "...../sum.py";
            // convert input arguments to JSON string
            BsonDocument argsBson = BsonDocument.Parse("{ 'x' : '1', 'y' : '2' }");

            bool saveInputFile = false;
        
            string argsFile = string.Format("{0}\\{1}.txt", Path.GetDirectoryName(pyScriptPath), Guid.NewGuid());

            string outputString = null;
            // create new process start info 
            ProcessStartInfo prcStartInfo = new ProcessStartInfo
            {
                // full path of the Python interpreter 'python.exe'
                FileName = "python.exe", // string.Format(@"""{0}""", "python.exe"),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = false
            };

            try
            {    
                // write input arguments to .txt file 
                using (StreamWriter sw = new StreamWriter(argsFile))
                {
                    sw.WriteLine(argsBson);
                    prcStartInfo.Arguments = string.Format("{0} {1}", string.Format(@"""{0}""", pyScriptPath), string.Format(@"""{0}""", argsFile));
                }
                // start process
                using (Process process = Process.Start(prcStartInfo))
                {
                    // read standard output JSON string
                    using (StreamReader myStreamReader = process.StandardOutput)
                    {
                        outputString = myStreamReader.ReadLine();
                        process.WaitForExit();
                    }
                }
            }
            finally
            {
                // delete/save temporary .txt file 
                if (!saveInputFile)
                {
                    File.Delete(argsFile);
                }
            }
            Console.WriteLine(outputString);
        }
    }
}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow