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)
Jamie Marshall
  • 1,885
  • 3
  • 27
  • 50

1 Answers1

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
Fabien
  • 4,862
  • 2
  • 19
  • 33
  • 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. – Jamie Marshall Jul 13 '17 at 02:34
  • I'm playing with this now. How do I direct one to log-file and one to pipe? There's good examples [here](https://stackoverflow.com/questions/8925323/redirection-of-standard-and-error-output-appending-to-the-same-log-file), but how do direct to two separate places on one call? `-RedirectStandardOutput` seems to only accept a file? – Jamie Marshall Jul 13 '17 at 03:19
  • 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. – Fabien Jul 13 '17 at 19:53