C#에서 파이썬 스크립트를 실행하려면 어떻게 해야 합니까?
이런 질문은 이전에도 여러 가지 정도로 질문이 있었지만, 저는 그것이 간결하게 답변되지 않았다고 생각하여 다시 질문합니다.
파이썬에서 스크립트를 실행하고 싶습니다.예를 들어 다음과 같습니다.
if __name__ == '__main__':
with open(sys.argv[1], 'r') as f:
s = f.read()
print s
파일 위치를 가져오고, 읽고, 내용을 인쇄합니다.그렇게 복잡하지는 않습니다.
좋아요, C#에서 이걸 어떻게 실행하죠?
이것이 제가 지금 가지고 있는 것입니다.
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;
start.Arguments = args;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
나▁the를 지날 때.code.py
는 위의치로입니다.cmd
리고그고.filename
는 위의치로입니다.args
동작되지 않습니다.는 합격해야 한다고 들었습니다.python.exe
▁the로서cmd
,그리고 나서.code.py filename
▁the로서args
.
제가 지금 한참을 찾았는데 아이언 파이썬 등을 사용해보겠다는 사람들만 보입니다.하지만 C#에서 파이썬 스크립트를 호출하는 방법이 있어야 합니다.
몇 가지 설명:
C#에서 실행해야 하고, 출력을 캡처해야 하며, IronPython이나 다른 것을 사용할 수 없습니다.어떤 해킹이든 좋습니다.
추신: 제가 실행하고 있는 실제 파이썬 코드는 이것보다 훨씬 더 복잡하며, C#에 필요한 출력을 반환하며, C# 코드는 끊임없이 파이썬 코드를 호출할 것입니다.
이것이 내 코드인 것처럼 가정합니다.
private void get_vals()
{
for (int i = 0; i < 100; i++)
{
run_cmd("code.py", i);
}
}
않는 있기 입니다.UseShellExecute = false
.
를 python 실행 파일로 .FileName
그리고 구축합니다.Arguments
스크립트와 읽을 파일을 모두 제공하는 문자열입니다.
참고로, 당신은 할 수 없습니다.RedirectStandardOutput
~하지 않는 한UseShellExecute = false
.
python에 대해 인수 문자열을 어떻게 포맷해야 할지 잘 모르겠지만, 다음과 같은 것이 필요할 것입니다.
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "my/full/path/to/python.exe";
start.Arguments = string.Format("{0} {1}", cmd, args);
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
{
using(StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
IronPython을 사용할 의향이 있다면 C#:에서 직접 스크립트를 실행할 수 있습니다.
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
private static void doPython()
{
ScriptEngine engine = Python.CreateEngine();
engine.ExecuteFile(@"test.py");
}
C에서 Python 스크립트 실행
C# 프로젝트를 생성하고 다음 코드를 작성합니다.
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
run_cmd();
}
private void run_cmd()
{
string fileName = @"C:\sample_script.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"C:\Python27\python.exe", fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine(output);
Console.ReadLine();
}
}
}
Python sample_script
"Python C# 테스트" 인쇄
C#의 콘솔에 'Python C# Test'가 표시됩니다.
저도 같은 문제에 부딪혔지만 도덕의 스승님의 대답은 제게 도움이 되지 않았습니다.다음은 이전 답변을 기반으로 한 것으로, 효과가 있었습니다.
private void run_cmd(string cmd, string args)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = cmd;//cmd is full path to python.exe
start.Arguments = args;//args is path to .py file and any cmd line args
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using(Process process = Process.Start(start))
{
using(StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
}
들어 는 "cmd"입니다.@C:/Python26/python.exe
는 고리 args일 입니다.C://Python26//test.py 100
100httptest.py 을 .py 을 ..py 파일 경로에 @ 기호가 없습니다.
실제로 Csharp(VS)와 Python과 IronPython을 통합하는 것은 매우 쉽습니다.그렇게 복잡하진 않아요Chris Dunaway가 답변 섹션에서 이미 말했듯이 저는 제 프로젝트를 위해 이 통합을 구축하기 시작했습니다.꽤 간단합니다.다음 단계만 수행하면 결과를 얻을 수 있습니다.
1단계: VS를 열고 빈 콘솔 앱 프로젝트를 새로 만듭니다.
2단계 : 도구 --> NuGet Package Manager --> Package Manager 콘솔로 이동합니다.
3단계 : 이후 브라우저에서 이 링크를 열고 NuGet 명령을 복사합니다.링크: https://www.nuget.org/packages/IronPython/2.7.9
4단계 : 위 링크를 연 후 PM > Install-Package IronPython - Version 2.7.9 명령을 복사하여 VS의 NuGet Console에 붙여넣습니다.지원 패키지를 설치합니다.
5단계 : Python.exe 디렉토리에 저장된 .py 파일을 실행하기 위해 사용한 코드입니다.
using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
}
6단계 : 코드 저장 및 실행
WorkingDirectory를 설정하거나 인수에서 python 스크립트의 전체 경로를 지정합니다.
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Python27\\python.exe";
//start.WorkingDirectory = @"D:\script";
start.Arguments = string.Format("D:\\script\\test.py -a {0} -b {1} ", "some param", "some other param");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
Console.Write(result);
}
}
저도 같은 문제가 있었고 여기에 있는 답변을 사용하여 프로세스를 사용하여 해결했습니다..NET과 IronPython 사이에 충돌이 있어서 거기서 성공하지 못했습니다.이것은 내 파이썬 3.10과 잘 작동합니다.
public void Run_cmd2(string exe, string args, string output )
{
var outputStream = new StreamWriter(output);
// create a process with the name provided by the 'exe' variable
Process cmd = new Process();
cmd.StartInfo.FileName = exe;
//define you preference on the window and input/output
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
// write the output to file created
cmd.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
if (!String.IsNullOrEmpty(e.Data))
{
outputStream.WriteLine(e.Data);
}
});
cmd.Start();
// write to the console you opened. In this case for example the python console
cmd.StandardInput.WriteLine(args);
//Read the output and close everything. make sure you wait till the end of the process
cmd.BeginOutputReadLine();
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
//close the process. writing to debug helps when coding
outputStream.Close();
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.Close();
Debug.WriteLine("\n\n Process done!");
//Console.ReadLine();
}
호출 예:
string pythonEngine = "C:\ProgramData\"아나콘다3\envs\compVision\python.exe";
string pythonArguments = "importos; os.chdir('C:\YourPath\excelWorkbooks'); testSearch 가져오기; testSearch.performAdd(2, 3);"
여기서 testSearch.py 의 함수를 호출합니다..py를 직접 실행하려면 다음을 수행합니다.
string pythonArguments = "importos; os.chdir('C:\YourPath\excelWorkbooks'); testSearch 가져오기; testSearch.py ";
outFile = "C:\사용자 경로\출력.txt";
_사용자의 모듈 이름.Run_cmd2(pythonEngine, pythonArguments, outFile);
는 에문가있다니습제▁with다에 문제가 있습니다.stdin/stout
페이로드 크기가 몇 킬로바이트를 초과하면 중단됩니다.파이썬 함수를 몇 가지 짧은 인수뿐만 아니라 크기가 클 수 있는 사용자 지정 페이로드로 호출해야 합니다.
얼마 전, 저는 레디스를 통해 다른 기계에 작업을 분산시킬 수 있는 가상 배우 라이브러리를 작성했습니다.Python 코드를 호출하기 위해 Python의 메시지를 듣고 처리한 후 결과를 다시 .NET에 반환하는 기능을 추가했습니다.다음은 작동 방식에 대한 간단한 설명입니다.
단일 시스템에서도 작동하지만 Redis 인스턴스가 필요합니다.Redis는 일부 신뢰성 보장을 추가합니다. 즉, 작업 완료를 확인할 때까지 페이로드가 저장됩니다.작업된 작업이 중단되면 페이로드는 작업 대기열로 반환된 다음 다른 작업자에 의해 재처리됩니다.
같은 확신을 가지고 있었고 이것은 나에게 효과가 있었습니다.
using IronPython.Hosting;
var engine = Python.CreateEngine();
engine.ExecuteFile("") //put the directory of the program in the quote marks
언급URL : https://stackoverflow.com/questions/11779143/how-do-i-run-a-python-script-from-c
'sourcecode' 카테고리의 다른 글
스프링 부트의 다중 변환 서비스 (0) | 2023.07.22 |
---|---|
C에서 인쇄 매크로 디버그? (0) | 2023.07.22 |
R의 벡터 목록에서 행렬을 만들려면 어떻게 해야 합니까? (0) | 2023.07.17 |
새 열을 추가한 후 SQL Server 열 이름이 잘못되었습니다. (0) | 2023.07.17 |
블로그를 위한 mongodb 스키마 설계 (0) | 2023.07.17 |