Home >Backend Development >C++ >How Can I Execute Python Scripts from C# Efficiently?
Using the
class of C#can easily execute the Python script, but there are many discussions on this method on the Internet, but there are few simple and efficient solutions.
Process
First, set
to directly control the executable file and its parameters. In addition, UseShellExecute
should specify the complete path of Python executable file. false
FileName
Next, build a
files, Arguments
should be code.py
. file.txt
Arguments
The following is the improved C#code: code.py file.txt
In order to continuously call the Python script, you can consider using the
cycle of the<code class="language-csharp">private void run_cmd(string cmd, string args) { ProcessStartInfo start = new ProcessStartInfo(); start.FileName = @"C:\Path\to\python.exe"; // 请修改为正确的Python可执行文件路径 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); } } }</code>method.
The above is the detailed content of How Can I Execute Python Scripts from C# Efficiently?. For more information, please follow other related articles on the PHP Chinese website!