在C#下运行Python可能有不同的原因。其中一些原因包括:
为实现Python和C#之间的互操作性,有两个库可供选择:IronPython和pythonnet:
根据具体的用例和要求,选择适合的库将提供更好的灵活性和互操作性。
下面使用 c#和IronPython 写一段获取天气的热门旅游城市的代码,首先是c#代码部分:
using IronPython.Hosting;
using IronPython.Runtime;
using Microsoft.Scripting.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace WeatherInfo
{
class Program
{
static void Main(string[] args)
{
// 亿牛云 爬虫代理加强版
// 设置爬虫代理IP的主机、端口、用户名和密码
string proxyHost = "www.16yun.cn";
int proxyPort = 31000;
string proxyUsername = "16YUN";
string proxyPassword = "16IP";
// 创建Python脚本引擎
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
// 设置代理IP
engine.GetSysModule().SetVariable("proxy_host", proxyHost);
engine.GetSysModule().SetVariable("proxy_port", proxyPort);
engine.GetSysModule().SetVariable("proxy_username", proxyUsername);
engine.GetSysModule().SetVariable("proxy_password", proxyPassword);
// 加载并执行Python脚本
engine.ExecuteFile("get_weather.py", scope);
// 获取结果
var cities = (List<string>)scope.GetVariable("cities");
var temperatures = (List<string>)scope.GetVariable("temperatures");
var times = (List<string>)scope.GetVariable("times");
// 创建XML文档
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement("WeatherData");
xmlDoc.AppendChild(root);
for (int i = 0; i < cities.Count; i++)
{
XmlElement cityElement = xmlDoc.CreateElement("City");
cityElement.SetAttribute("Name", cities[i]);
XmlElement temperatureElement = xmlDoc.CreateElement("Temperature");
temperatureElement.InnerText = temperatures[i];
XmlElement timeElement = xmlDoc.CreateElement("Time");
timeElement.InnerText = times[i];
cityElement.AppendChild(temperatureElement);
cityElement.AppendChild(timeElement);
root.AppendChild(cityElement);
}
// 保存XML文件
xmlDoc.Save("weather_data.xml");
Console.WriteLine("Weather information saved to weather_data.xml.");
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/31528575/viewspace-2960534/ ,如需转载,请注明出处,否则将追究法律责任。