Calling Python script from C # - Changing the script file path causes the program to not work
The following code works without error:
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);
}
}
However, when I change the path to getWeather.py to not be in an arbitrary random place like:
string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";
Then my program no longer receives the script output. The script is still working: I ran it with IDLE and it exited as expected. When I call it using C #, the console opens, but the result is not working.
The Python script looks like this:
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"]))
(He looks at my local weather)
Check out PySharp.ExecutePy () here
By far the strangest error I have ever encountered. Any ideas?
EDIT 1: It seems like C # is actually reading something from a script. It just seems like it's something ... nothing. I gave the shortcut a sample default text, and after running the program, the shortcut text is simply replaced with an empty string. Hope this incredible discovery helps somehow.
EDIT 2: The program cannot call the script correctly when its file path contains spaces . For example:
C:\foo bar\testing\pyWeather.py
does not work!
source to share
Try to surround a path containing spaces with two double quotes.
For example,
string pyWeather = @"""C:\Users\[myname]\Documents\Visual Studio 2017\Projects\testing\testing\scripts\getWeather.py""";
Similarly, you can do string pyWeather = Directory.GetCurrentDirectory() + @"\scripts\getWeather.py";
and then pyWeather = "\"" + pyWeather + "\"";
.
source to share
I want you to return a response instead of printing. A printer is an I / O solution for display. This way it will work fine with IDLE, however it may not return the results as you expected. I strongly believe that this will solve your problem. try going back instead of printing. I can give additional support after trying this.
return(str(container["data-title"]))
source to share