Reputation: 65
I'm sorry if this may be an existing question but I'm having a hard time to execute this.
I have this simple python code where it asks user to input a number and multiply it by 2.
userInput = int({sys.argv[1]})
pythonOutput = userInput * 2
print("The number passed is: ", pythonOutput)
What I want do is for the user to enter the number in C# Winforms then also display the result in C#. So, the number needed for userInput from python code will come from C# and then the output from python code will be displayed in C#
This is currently my C# code
string pythonInterpreter = @"C:\Anaconda3\python.exe";
var start = new ProcessStartInfo
{
FileName = pythonInterpreter,
Arguments = string.Format($"\"{@"C:\Users\chesk\Desktop\Work Files\Project\Thermal Camera\PythonForC#\SimpleInputOutput.py"}\" {txtUserInput.Text}"),
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = true,
};
var result = "0";
var error = "";
using (Process process = Process.Start(start))
{
result = process.StandardOutput.ReadToEnd();
error = process.StandardError.ReadToEnd();
lblPythonOutput.Text = result;
lblPythonOutputError.Text = error;
}
EDIT:
I updated both my python and c# codes and I can now pass value in python using C# but when sending an integer, this error appeared.
Traceback (most recent call last): File"C:\Users\chesk\Desktop\Work Files\Project\Thermal Camera\PythonForC#\SimpleInputOutput.py", line 8, in userInput = int({sys.argv[1]}) TypeError: int() argument must be a string, a bytes-like object or a number, not 'set'
Final Edit: So, it turns out that the c# code is really working but I need to modify my python code. So here it is.
userInput = int(sys.argv[1])
pythonOutput = userInput * 2
print("The number passed is: ", pythonOutput)
Hope this will help someone!
Upvotes: 1
Views: 591
Reputation: 684
The C# code doesn't look to bad. I think the issue is with your python code, because it's asking for userinput. But you're already passing the number as a command line argument to your python script, so it doesn't need to ask for user input. Instead you should use the argument passed to the python script.
Here is an example:
import sys
print(f"The number passed by c# was: {sys.argv[1]}")
You can checkout this tutorial about python command line arguments for more information
Edits:
Changed sys.argv[0] to sys.argv[1] - Thanks Roy Cohen
Changed to f-strings - Thanks Roy Cohen
Upvotes: 2