I am trying to get the installed version of python from a pc using c# (as a part of a WinForms app). I'm trying to do so by creating a new subprocess following these two threads here and here , but none seems to work...
I've tried changing the fields of the process constructor the other way around to:
UseShellExecute = true
RedirectStandardOutput = false
CreateNoWindow = false
and it seems that the Arguments
does not even passed to the subprocess so nothing will be outputted..(it just opens a cmd window regularly)
What am i missing?
This is the current code
Its a rough and initial code, and will change once i get the output messages..
*both methods seems to start the cmd process but it just gets stuck and does not output anything, even without redirection.
private bool CheckPythonVersion()
{
string result = "";
//according to [1]
ProcessStartInfo pycheck = new ProcessStartInfo();
pycheck.FileName = @"cmd.exe"; // Specify exe name.
pycheck.Arguments = "python --version";
pycheck.UseShellExecute = false;
pycheck.RedirectStandardError = true;
pycheck.CreateNoWindow = true;
using (Process process = Process.Start(pycheck))
{
using (StreamReader reader = process.StandardError)
{
result = reader.ReadToEnd();
MessageBox.Show(result);
}
}
//according to [2]
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = "python --version",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
result = proc.StandardOutput.ReadLine();
// do something with result
}
//for debug purposes only
MessageBox.Show(result);
if (!String.IsNullOrWhiteSpace(result))
{
MessageBox.Show(result);
return true;
}
return false;
}
CodePudding user response:
- Python is
python.exe
, so you can run it directly. You don't needcmd.exe
. It just makes things more complicated. - You redirect
StandardError
, but that's not where the version information is written to. RedirectStandardOutput
instead. - This whole approach will only work if Python has been added to the
%PATH%
environment variable. If it was installed without that, Python will not be found.
With 3. in mind, the code which works for me:
void Main()
{
var p = new PythonCheck();
Console.WriteLine(p.Version());
}
class PythonCheck {
public string Version()
{
string result = "";
ProcessStartInfo pycheck = new ProcessStartInfo();
pycheck.FileName = @"python.exe";
pycheck.Arguments = "--version";
pycheck.UseShellExecute = false;
pycheck.RedirectStandardOutput = true;
pycheck.CreateNoWindow = true;
using (Process process = Process.Start(pycheck))
{
using (StreamReader reader = process.StandardOutput)
{
result = reader.ReadToEnd();
return result;
}
}
}
}
Output:
Python 3.9.7