StreamReader.ReadLine()在C#中返回空字符串

时间:2017-01-20 16:00:39

标签: .net visual-studio python-3.x c#-4.0 botframework

我正在使用Microsoft Bot Framework制作一个会话天气聊天机器人。

  • 在Controller类中,我调用了Weather类的getWeather()方法。
  • 在getWeather方法中,我正在运行一个python脚本来进行API调用。
  • 现在我正在将python脚本的标准输出重定向到我正在通过字符串阅读的StreamReader对象。

然而,StreamReader对象返回一个空字符串。有人可以帮帮我吗?

Python脚本:

import requests
city = "something"
APIkey = "something"
r = requests.post('http://api.openweathermap.org/data/2.5/weather?q='+city+'&APPID='APIkey)
json_obj = r.json()
print(json_obj['weather'][0]['description'])

当我在python shell中运行此脚本时,我将其作为输出:

haze

MessagesController.cs类

public class MessagesController : ApiController
{
        public async Task<HttpResponseMessage> Post([FromBody]Activity activity)
        {
            if (activity.Type == ActivityTypes.Message)
            {
                ConnectorClient connector = new ConnectorClient(new Uri(activity.ServiceUrl));
                // calculate something for us to return
                string s = activity.Text;
                Weather w = new Weather();
                s = w.getWeather(s);
                // return our reply to the user
                Activity reply = activity.CreateReply(s);
                await connector.Conversations.ReplyToActivityAsync(reply);
            }
            else
            {
                HandleSystemMessage(activity);
            }
            var response = Request.CreateResponse(HttpStatusCode.OK);
            return response;
        }
}

Weather类

中的getWeather()方法
public string getWeather(string s)
        {
            ProcessStartInfo pythonInfo = new ProcessStartInfo();
            Process python;
            StreamReader sr;
            pythonInfo.FileName = @"somepath\python.exe";
            pythonInfo.Arguments = @"somepath\file.py";
            pythonInfo.CreateNoWindow = false;
            pythonInfo.UseShellExecute = false;
            pythonInfo.RedirectStandardOutput = true;
            Debug.WriteLine("Python Starting");
            python = Process.Start(pythonInfo);
            Debug.WriteLine("Python Started");
            sr = python.StandardOutput;
            Debug.WriteLine("passed standard output to sr");
            string text = sr.ReadLine();
            Debug.WriteLine(sr.ReadLine());
            Debug.WriteLine(text);
            python.WaitForExit();
            python.Close();
            sr.Close();
            return text;
        }

文本作为空字符串返回,而不是python脚本给出的输出。请帮忙!

0 个答案:

没有答案