C #에서 Python 확장을 어떻게 실행 확장?
이런 종류의 질문은 이전에 다양한 수준으로 요청되는 간결한 방식으로 답변없는 것 같은 것입니다.
가능성에서 펼쳐를 실행하고 싶습니다. 이것이 이것이라고 가정 해봅시다.
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);
}
}
}
하지 않는 작동 위치 와 code.py
위치를 전달하면 내가 통과해야 우리 들었다 는 AS 후, 은 AS .cmd
filename
args
python.exe
cmd
code.py filename
args
나는 잠시 동안 IronPython 등을 사용 제안하는 사람들 만 수 있습니다. 그러나 C #에서 Python 펼쳐야합니다.
몇 가지 설명 :
IronPython 또는 IronPython 또는 다른 것을 사용할 수 없습니다. 해킹이 무엇이든 괜찮을 것입니다.
추신 : 내가 실행중인 실제 Python 코드는 이것보다 훨씬 복잡하며 C #에서 필요한 출력을 반환하며 C # 코드는 계속해서 Python을 호출합니다.
이것이 내 코드 인 척 :
private void get_vals()
{
for (int i = 0; i < 100; i++)
{
run_cmd("code.py", i);
}
}
작동하지 않는 이유는 귀하가 있기 때문 UseShellExecute = false
입니다.
셸을 사용하지 않는 파이썬 실행 파일의 전체 경로를 로 제공하고 펼쳐 읽을 파일을 모두 제공 FileName
하는 Arguments
것을 작성해야합니다.
또한 RedirectStandardOutput
제외 하고는 할 수 없습니다 UseShellExecute = false
.
어느 쪽에서 인수의 형식을 지정하는 방법을 잘 모르겠지만 다음과 같은 것이 필요합니다.
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 # 테스트' C 번호의 콘솔에서.
나는 같은 문제에 부딪 쳤고 Master Morality의 대답이 나를 위해 해주지 않았습니다. 이전 답변을 기반으로 한 다음이 작동했습니다.
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 행 인수 100을 사용하여 test.py를 실행하려는 경우 cmd가 @C:/Python26/python.exe
되고 args가 C://Python26//test.py 100
됩니다. .py 파일의 경로에 @ 기호가 없습니다.
이것에주의를 끌기 위해서 :
https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee
잘 작동합니다.
WorkingDirectory를 설정하거나 Argument에 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);
}
}
실제로 Csharp (VS)와 Python을 IronPython과 통합하는 것은 매우 쉽습니다. 그렇게 복잡하지는 않습니다 ... Chris Dunaway가 이미 답변 섹션에서 말했듯이 저는 제 프로젝트를 위해이 통합을 구축하기 시작했습니다. N 꽤 간단합니다. 다음 단계를 따르기 만하면 결과를 얻을 수 있습니다.
1 단계 : VS를 열고 비어있는 새 ConsoleApp 프로젝트를 만듭니다.
2 단계 : 도구-> NuGet 패키지 관리자-> 패키지 관리자 콘솔로 이동합니다.
3 단계 : 브라우저에서이 링크를 열고 NuGet 명령을 복사합니다. 링크 : https://www.nuget.org/packages/IronPython/2.7.9
4 단계 : 위 링크를 연 후 PM> Install-Package IronPython -Version 2.7.9 명령을 복사하여 VS의 NuGet 콘솔에 붙여 넣습니다. 지원 패키지를 설치합니다.
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 단계 : 코드 저장 및 실행
문제가 stdin/stout
있습니다. 페이로드 크기가 수 킬로바이트를 초과하면 중단됩니다. 짧은 인수뿐만 아니라 커질 수있는 사용자 지정 페이로드를 사용하여 Python 함수를 호출해야합니다.
얼마 전에 저는 Redis를 통해 다른 컴퓨터에 작업을 배포 할 수있는 가상 액터 라이브러리를 작성했습니다. Python 코드를 호출하기 위해 Python에서 메시지를 수신하고 처리 한 다음 결과를 .NET으로 반환하는 기능을 추가했습니다. 다음은 작동 방식에 대한 간략한 설명입니다 .
단일 머신에서도 작동하지만 Redis 인스턴스가 필요합니다. Redis는 몇 가지 안정성 보장을 추가합니다. 페이로드는 작업이 완료되었음을 확인할 때까지 저장됩니다. 작업이 종료되면 페이로드가 작업 대기열로 반환 된 다음 다른 작업자가 다시 처리합니다.
참고 URL : https://stackoverflow.com/questions/11779143/how-do-i-run-a-python-script-from-c
'IT' 카테고리의 다른 글
패키지 서브 디렉토리의 Python Access 데이터 (0) | 2020.08.02 |
---|---|
Postgres의 테이블에 여러 열을 추가하는 방법은 무엇입니까? (0) | 2020.08.02 |
NgFor는 Angular2에서 파이프로 데이터를 업데이트하지 않습니다. (0) | 2020.08.02 |
웹뷰에서 HTML 콘텐츠를 얻는 방법? (0) | 2020.08.02 |
html, CSS로 코드를 작성하는 올바른 방법 (0) | 2020.08.02 |