-1

I try to call from C# a python script divided in many functions. With these parts of code output is empty.

import sys
def main():
    print('Hello')
    if len(sys.argv) >=3:
        x = sys.argv[1]
        y = sys.argv[2]
        # print concatenated parameters
        main2(x,y)
def main2(x,y):
    print(x+y)
if __name__=='__main__':
    main()

C#:

int x = 1;
int y = 2;
string progToRun = "main.py";
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Program Files\Python37\python.exe";
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = string.Concat(progToRun, " ", x.ToString(), " ", y.ToString());
proc.Start();
StreamReader sReader = proc.StandardOutput;
string output = sReader.ReadToEnd();
proc.WaitForExit();
Console.ReadLine();

With this python script it works:

import sys

def main():
    print('Hello')
    if len(sys.argv) >=3:
        x = sys.argv[1]
        y = sys.argv[2]
        # print concatenated parameters
        print(x+y)


if __name__=='__main__':
    main()

What's the difference between the two pyhton scripts? How can I use in C# a python script with many functions? Can I execute a python script wihtout sending parameters(x and y)?

Thank You.

  • 1
    If you only to simplistic things, use [iron python](https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app) – Patrick Artner Apr 09 '19 at 20:26

1 Answers1

1

Basically, in your first Python code block, you get the error local variable 'x' referenced before assignment Your indentation for the call to main2(x,y) is 1 level back.

You'll want to add an indentation level to the like main2(x,y)

SharpNip
  • 350
  • 3
  • 9
  • Sorry. I modified the python code block but this doesn't change anything. – Claudinho18 Apr 09 '19 at 21:13
  • Then other than the "What's the difference between the two pyhton scripts?" what exactly is your question/issue? – SharpNip Apr 10 '19 at 00:58
  • HI! The problem is that i have to execute an python script with many functions which call each other( like in first python code block) and the string output has no value, is empty and for second python code block this string has value and i don't understand what is wrong. – Claudinho18 Apr 10 '19 at 06:19
  • As @Patrick Artner suggested, you may want to look into Iron Python for Python + .Net related stuff. Take a look at this previously asked question: https://stackoverflow.com/questions/7053172/how-can-i-call-ironpython-code-from-a-c-sharp-app?noredirect=1&lq=1 – SharpNip Apr 10 '19 at 13:41
  • Also, just double checked again and in both cases, on my end, I'm getting "Hello\r\n12\r\n". – SharpNip Apr 10 '19 at 13:59
  • There was a difference on the indentation. The call of function main2 was at 2 tabs and the other lines were at 8 spaces. Apparently was same indentation but in reality no. Thank you. – Claudinho18 Apr 10 '19 at 16:58