Catching runtime exceptions and outputs from python script in c# -
i'm writing wcf service runs python scripts.
for i've been using following code:
processstartinfo start = new proccessstartinfo(); start.filename = "my/full/path/to/python.exe"; start.arguments = string.format("{0} {1}", script, args); start.useshellexecute = false; start.createnowindow = true; start.redirectstandardoutput = true; start.redirectstandarderror = true; process p = new process(); p.startinfo = start; p.start(); p.waitforexit(); string stderr = process.standarderror.readtoend(); string stdout = process.standardoutput.readtoend();
now i've noticed (after lot of testing) process object gets standard error/output or catches exception if error related "compilation" errors, if have undeclared variable used or stuff that, runtime exceptions , prints not being caught or able read in c# scope.
i've tried run either whole "python.exe pythoncommand.py args" sent c# code or send in processstartinfo.arguments in command line prompt , returned exceptions , prints in both cases, still when run via c# process object no exceptions thrown @ me catch , no output or error ever.
i've found nothing makes me feel kind of stupid (hopefully , has simple solution), , appreciate if has stumbled upon case me out.
thanks, matt
well, answer comment here:
but problem both exception not being thrown the python nor output read. standard output of process (and standard error well) empty – matt star
you capturing output wrong. allow capture output , should show exceptions thrown.
using system; using system.diagnostics;
namespace interactwithconsoleapp { class program { static void main(string[] args) { processstartinfo cmdstartinfo = new processstartinfo(); cmdstartinfo.filename = @"c:\windows\system32\cmd.exe"; cmdstartinfo.redirectstandardoutput = true; cmdstartinfo.redirectstandarderror = true; cmdstartinfo.redirectstandardinput = true; cmdstartinfo.useshellexecute = false; cmdstartinfo.createnowindow = true; process cmdprocess = new process(); cmdprocess.startinfo = cmdstartinfo; cmdprocess.errordatareceived += cmd_error; cmdprocess.outputdatareceived += cmd_datareceived; cmdprocess.enableraisingevents = true; cmdprocess.start(); cmdprocess.beginoutputreadline(); cmdprocess.beginerrorreadline(); cmdprocess.standardinput.writeline("ping www.bing.com"); //execute ping bing.com cmdprocess.standardinput.writeline("exit"); //execute exit. cmdprocess.waitforexit(); } static void cmd_datareceived(object sender, datareceivedeventargs e) { console.writeline("output other process"); console.writeline(e.data); } static void cmd_error(object sender, datareceivedeventargs e) { console.writeline("error other process"); console.writeline(e.data); } } }
i copied code post: how parse command line output c#? have used method many times , works perfect. hope helps.
Comments
Post a Comment