**
c#通过命令行调用python代码
**
即相当于在spyder控制台中直接运行:runfile(‘test.py’, args=r’“你的路径” 4’)
实现了异步实时显示,输出即为直接调用python的print的输出参数,显示在c#ui的textbox3中,每次print一次,就显示一个,而不是都运行完了再一次输出。
参考该链接:https://blog.csdn.net/coco_1998_2/article/details/88885929
c#代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace MS_UI
{
public partial class FrmParamSet : Form
{
private string inputPath;
// 声明一个委托来更新 TextBox
delegate void UpdateTextBoxDelegate(string text);
public FrmParamSet()
{
InitializeComponent();
txtPath.Text = "你的路径";//输入参数1
textBox1.Text = "4"; //输入参数2
}
private void UpdateTextBox(string text)
{
if (textBox3.InvokeRequired)
{
// 如果调用线程不是创建控件的线程,通过调用 Invoke 方法将操作传递到创建控件的线程
textBox3.Invoke(new UpdateTextBoxDelegate(UpdateTextBox), new object[] { text });
}
else
{
textBox3.AppendText(text + Environment.NewLine); // 将输出追加到 TextBox 中
}
}
private void but_path_Click(object sender, EventArgs e)
{
folderBrowserDialog1.Description = "请选择文件夹";
folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
folderBrowserDialog1.ShowNewFolderButton = true;
if (txtPath.Text.Length > 0) folderBrowserDialog1.SelectedPath = txtPath.Text;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowserDialog1.SelectedPath;
}
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void label7_Click(object sender, EventArgs e)
{
}
private async void btn_save_Click_Click(object sender, EventArgs e)
{
string[] strArr = new string[2];//参数列表
//int numberArgument = 5;
string sArgName = @"test.py"; //调用的python的文件名字
string a = txtPath.Text;
int b = int.Parse(textBox1.Text);
//RunPythonScript(sArguments,a, b);
// 执行 Python 脚本,计算并返回结果
string pathParameter = a;
int numberParameter = b;
string result = await RunPythonScript(sArgName, pathParameter,numberParameter);
textBox3.AppendText(result + Environment.NewLine);
}
//
// 在类的成员变量中定义一个 StringBuilder 对象用于保存输出结果
StringBuilder outputText = new StringBuilder();
private async Task<string> RunPythonScript(string sArgName, string a, int b)
// private string RunPythonScript(string sArgName ,int a, int b)
{
string path = @"Z:\pycsharp\" + sArgName;
string args = $"{a} {b}";
StringBuilder outputText = new StringBuilder();
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo
{
FileName = @"G:\anaconda_2023\envs\py36\python.exe",//调用的python环境
Arguments = $"{path} {args}",
UseShellExecute = false,
RedirectStandardOutput = true, //通过RedirectStandardOutput = true设置,我们告诉操作系统在执行外部进程时捕获它的标准输出流
CreateNoWindow = true,
};
process.OutputDataReceived += (sender, e) =>
{
if (e.Data != null)
{
Console.WriteLine(e.Data);
outputText.AppendLine(e.Data);
UpdateTextBox(e.Data); // 在 UI 线程中更新 TextBox
}
};
process.Start();
process.BeginOutputReadLine();
await Task.Run(() =>
{
process.WaitForExit();
});
return outputText.ToString().Trim();
}
}
}
python部分关键代码,最重要的为 sys.stdout.flush() 进行 强制刷新输出,否则无法实现实时显示。以下代码不能运行,只为说明关键代码。如下:
```python
from io import BytesIO
if __name__ == '__main__':
# 第一个参数是传递过来的路径字符串参数,之后的参数是传递过来的其他参数
folder_path = sys.argv[1]
num1 = int(sys.argv[2])
for i, file_name in enumerate(file_list):
file_path = os.path.join(folder_path, file_name)
if (y_qujian[1]-y_qujian[0])<2.5:
continue
else:
keyp_data = find_keyp1(xnew,ynew,num1)
sys.stdout.flush() # 强制刷新输出
time.sleep(0.1)