-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
  • 1
    If you only to simplistic things, use iron python Commented Apr 9, 2019 at 20:26

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

6 Comments

Sorry. I modified the python code block but this doesn't change anything.
Then other than the "What's the difference between the two pyhton scripts?" what exactly is your question/issue?
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.
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: stackoverflow.com/questions/7053172/…
Also, just double checked again and in both cases, on my end, I'm getting "Hello\r\n12\r\n".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.