0

I would like to output the stdout and stderr to two different log files. i have tried this code but it only outputs the error to error log , but output is not redirected to runtime.log file.

the code is being run on windows and mostly robocopy is done in the code.

saveerr = sys.stderr 
fsock = open('error.log', 'a') 
sys.stderr = fsock

saveout = sys.stdout
fsock1 = open('runtime.log', 'a') 
sys.stdout = fsock1

the sys.stdout area is not working. please let me know any correction in this code.

here is my entire code

import sys

saveerr = sys.stderr 
fsock = open('error.log', 'a') 
sys.stderr = fsock

saveout = sys.stdout
fsock1 = open('runtime.log', 'a') 
sys.stdout = fsock1

##For site  AUCB-NET-01   from source folder AUDC-RSTOR-01  E:\Canberra
exit_code1 = subprocess.call('robocopy \\\\aucb-net-01\\d$ \\\\nasaudc01\\remote_site_sync\\aucb-net-01  /E /MIR /W:2 /R:1', shell=True)
print ("exitcoode1=", exit_code1)

thanks to everyone for reading my post.

Lieven Keersmaekers
  • 57,207
  • 13
  • 112
  • 146
Ajsh
  • 62
  • 2
  • 10

1 Answers1

3

As mentioned in my comment your code should divert your stdout to the file. To get robocopy's stdout to go there too just echo each line to your stdout as shown in this link

https://stackoverflow.com/a/28319191/6550457


from subprocess import Popen, PIPE
import sys

saveerr = sys.stderr 
fsock = open('error.log', 'a') 
sys.stderr = fsock

saveout = sys.stdout
fsock1 = open('runtime.log', 'a') 
sys.stdout = fsock1

cmd = 'robocopy \\\\aucb-net-01\\d$ \\\\nasaudc01\\remote_site_sync\\aucb-net-01  /E /MIR /W:2 /R:1'
p = Popen(cmd, stdout=sys.stdout, stderror=sys.stderr, bufsize=1, universal_newlines=True)
exit_code1 = p.wait()

see @eryksuns comments about robo copy and it's exit codes. http://ss64.com/nt/robocopy-exit.html

Community
  • 1
  • 1
FloatingKiwi
  • 4,408
  • 1
  • 17
  • 41
  • i would like to do six robocopy in same this script , how can i do so ..... will the above script work for all six robocopy commands...... – Ajsh Aug 19 '16 at 08:58
  • yes, it'll work. You can either duplicate the last 4 lines 6 times over or create an array of cmd values and iterate over them – FloatingKiwi Aug 19 '16 at 09:18
  • No problem, if this has resolved your issue could you please tick the answer as accepted. – FloatingKiwi Aug 19 '16 at 11:50
  • 1
    It would be simpler to pass `Popen` the arguments `stdout=sys.stdout` and `stderr=sys.stderr`, and then check `p.wait()` for [robocopy's exit code](http://ss64.com/nt/robocopy-exit.html). The intermediating pipe and decoding of text aren't really necessary. – Eryk Sun Aug 19 '16 at 14:14
  • A lot of programs use a generic 0 for success and any other value is an error code, but robocopy uses information codes. So, for example, `subprocess.check_call` thinks robocopy has failed when it actually succeeded. I think that's worth noting, so can you include the link for the exit codes? – Eryk Sun Aug 20 '16 at 02:46