Sonetimes you need to run shell commands in your Python script, there are few different modules in python for that and the subprocess is one of those . Then you might need to copy the output of your shell command to a log file . This can be usually done with the append (>>) method in shell . But in some cases, this won’t work especially if you have lots of dynamic variables using with the shell commands . For eg : I need to run a dulpcate IP scan specificially to a dynamic gateway IP .So this gateway IP is grepped from the interface uisng ‘awk’, ‘sed’ etc and then assign to a variable . I will be then using this variable in the shell command . So to append subprocess.Popen output to a file
First , assign a variable to your log file location and open the file in append mode
log = open("/var/log/name.log","a")
Then assign your shell command to another variable:
command = subprocess.Popen('your shell command' ,stdout=log, stderr=log, shell=True)
That’s it , your output will be appended to your log file . Its better to use the subprocess.wait to fnish the execution of the command . This is very useful in running commands in long python scripts where you need to wait until the first command finishes.
command.wait()