0

I'm trying to execute a bash and want to redirect the output on the shell to a file

this is what I have so far

baby = subprocess.Popen('some command', stdout = subprocess.PIPE, shell = True)
print (baby.stdout.readlines()) #i wanna see it in console
with open("log.txt","a") as fobj: #wanna create a file log.txt and save the output there as string                                 
        fobj.write(stdout)

but I get this error NameError: name 'stdout' is not defined

I've looked at these question Run subprocess and print output to logging , subprocess.Popen() doesn't redirect output to file , Can you make a python subprocess output stdout and stderr as usual, but also capture the output as a string? but to no avail, they were all too complex for me, i got lost in all the code..

can't i just redirect the stdout to a normal txt file? and is there a way I can built a function to time the execution of that script and put it in that same log.txt file (i use time ./myscript.py to take the time but i also don't know how to redirect it to the txt file)

skdadle
  • 155
  • 1
  • 2
  • 17

1 Answers1

0

You should adjust this example however suits you

First create input.txt file

Then

import sys

with open(sys.argv[1], 'r') as input, open(sys.argv[2], 'w') as output:
    for line in input:
        output.write(str(line.strip()) + '\n')

You run it from command line(s4.py,you can rename it)

python s4.py input.txt output.txt

Output

obama
is
my boss

You can guess but output is same as input.

Richard Rublev
  • 7,718
  • 16
  • 77
  • 121