1

Is there a way in Powershell to redirect the print statements from python one place and the return statements to another place?

For instance i'm trying

$ python myPythonScript.py args >> logFile 

I get print statement output in my log file (though it looks awful, cleaning will be the next job)

However, i do not get the return statement values from the python in the output. Nor do i catch them if I use *>>

Any ideas what's happening?

Python Example:

def main(args) print "This goes to file" #parse flags... #do something here... MyVar = "Please " + "Work" return MyVar #doesn't go anywhere if(__name__ == '__main__': main(sys.argv) 
4
  • What is for you a "return statement" ? Commented Jul 13, 2017 at 2:07
  • Python example added Commented Jul 13, 2017 at 2:16
  • You can only return integers from your application, so you won't be able to get that string. You use echo %errorlevel% to print the returned int value of your python script. I will make an answer. Commented Jul 13, 2017 at 2:17
  • sys.stderr.write() Commented Jul 13, 2017 at 2:51

1 Answer 1

1

The return value of a program (or exit code) can only be an integer, not a string.

First, ensure you return an int, or do exit(n) where n is an int.

You might want to also fix:

if(__name__ == '__main__'): return main(sys.argv) 

You can then access the return value of your program (script) in Powershell with echo %errorlevel%

If you really want a string to be used by powershell, you should:

  1. print your logs on stderr instead of stdout
  2. print the filename on stdout at end of execution
  3. redirects stderr to your logfile and stdout to a powershell pipe | if you want a redirection - or you can execute the python script within parentheses $() so the result can be used on command line
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Fabien. How do I get the string I need though? In my actual program the string I need back is a file name - an integer won't work.
I'm playing with this now. How do I direct one to log-file and one to pipe? There's good examples here, but how do direct to two separate places on one call? -RedirectStandardOutput seems to only accept a file?
What you do is redirect stderr only, and stdout is naturally conveyed through a pipe. I recommend you also try the $() feature, it is helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.