我有一个简单的 python 程序,名为 hello.py
import sys
def Simple():
print "Hello from Python"
如何在位于 .aspx.cs 类型的 Web 窗体中的文本框中显示该程序的输出
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
TextBox1.Text = // Output of hello.py to be asigned to TextBox1.Text
}
最佳答案
您必须按照以下步骤来实现此目的。
在 CGI 中托管该 python 文件,假设链接是 http://localhost/cgi-bin/test.py
并使用 WebClient
调用它并得到输出。以下是使用 WebClient
调用 URL 的代码.
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
WebClient client = new WebClient();
string reply = client.DownloadString("http://localhost/cgi-bin/test.py"); // address = CGI hosted URL
TextBox1.Text = reply;
}
其他
假设:你在windows系统中安装了python。
- 将 python 脚本保存到文件中,例如 abc.py。
- 你可以直接执行python脚本,使用这个
"c:\python26\python.exe" "abc.py"
。我们将在下一步中使用它。 - 使用进程执行,我们可以从 C# 执行上述命令并获取输出。示例 -
var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "c:\python26\python.exe", Arguments = "abc.py", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); while (!proc.StandardOutput.EndOfStream) { string line = proc.StandardOutput.ReadLine(); // do something with line TextBox1.Text = line; }
或 - 使用此链接 http://blog.luisrei.com/articles/flaskrest.html
- 这显示了如何制作基于 REST 的 Python 代码,您可以直接调用 REST API
在 asp.net 代码中。
关于c# - 如何在 .aspx Web 表单中的文本框中显示 python 程序的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26492339/