从C#调用Python脚本-更改脚本';s文件路径导致程序无法运行
以下代码工作正常,没有任何缺陷:从C#调用Python脚本-更改脚本';s文件路径导致程序无法运行,c#,python,C#,Python,以下代码工作正常,没有任何缺陷: public partial class MainForm : Form { string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt"); string pyWeather = @"C:\getWeather.py"; public MainF
public partial class MainForm : Form
{
string pyInterp = File.ReadAllText(Directory.GetCurrentDirectory() + @"\config\pathToPythonInterpreter.txt");
string pyWeather = @"C:\getWeather.py";
public MainForm()
{
InitializeComponent();
UpdateWeather();
}
public void UpdateWeather()
{
labelWeather.Text = PySharp.ExecutePy(pyInterp, pyWeather);
}
}
但是,当我将getWeather.py的路径更改为不在任意随机位置时,如下所示:
string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";
然后我的程序不再获得脚本的输出。脚本仍然有效:我使用IDLE启动它,它正确地完成了它的功能。当我使用C#调用它时,控制台打开,但没有获得任何输出
Python脚本如下所示:
from requests import get
from bs4 import BeautifulSoup as soup
r = get("http://www.ilmateenistus.ee/ilm/prognoosid/4-oopaeva-prognoos/")
parsed = soup(r.content, "html.parser")
container = parsed.find("div",{"class":"point kuusiku"})
print(str(container["data-title"]))
(这影响了我当地的天气)
这是我遇到过的最奇怪的虫子。有什么想法吗
编辑1:看来C#确实在读剧本中的一些东西。看来这件事是。。没有什么。我给了标签一个默认的示例文本,在运行程序后,标签的文本被简单地更改为空字符串。希望这个不可思议的发现能有所帮助
编辑2:当程序的文件路径包含空格时,程序无法正确调用脚本。例如:
C:\foo bar\testing\pyWeather.py
不行 我希望您返回答案,而不是打印。打印机是一种基于I/O的显示解决方案。因此,它将在空闲时工作得非常好,但是它可能不会像您预期的那样返回结果。我坚信这会解决你的问题。 请尝试返回,而不是打印。我可以在尝试后给予更多的支持
return(str(container["data-title"]))
尝试用两个双引号包围包含空格的路径 例如
string pyWeather=@“C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py”“代码>
类似地,您可以执行string pyWeather=Directory.GetCurrentDirectory()++“\scripts\getWeather.py”代码>后跟pyWeather=“\”“+pyWeather+”\”代码> 我尝试过这个,我的第一个假设是您的脚本导致了一些错误。其输出被写入标准错误而不是标准输出。试着在python脚本中只执行print(“hello world”)
,看看它是否显示在表单上。稍后,添加一个try
/catch
以查看它是什么错误。GetCurrentDirectory
返回的值是多少?下面有“\scripts\getWeather.py”吗?如果在debug
下运行,请查找debug\bin
目录;如果在发布版本下运行,请查找release\bin
。将“scripts\getWeather.py”放在下面。顺便说一句,这条路径不是随机位置。嘿,shahkalpesh,我尝试在脚本和C#项目内部实现错误处理程序。不幸的是,什么也没抓到。我使用了Messagebox.Show()
来查看文件路径是否正确,实际上是否正确。现在我将尝试JAugust提出的解决方案。在string pyWeather=Directory.GetCurrentDirectory()+@“\scripts\getWeather.py”之后,pyWeather
的值是多少代码>?脚本文件是否存在于该路径上?我不这么认为。试着用两个双引号包围包含空格的路径。例如,string pyWeather=@“C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py”“代码>类似地,您可以执行string pyWeather=Directory.GetCurrentDirectory()++“\scripts\getWeather.py”代码>后跟pyWeather=“\”“+pyWeather+”\”嘿,我试过你的建议,但还是一无所获。我想提到的是,我问题中的第一个代码块仍然可以正常工作;是文件路径的更改突然中断了它,所以打印值不应该是原因。