I am having a service which run using a batch file in command prompt, I want to read the whole information running in the console and want to write it to an another file but I am able to write it only when the service is closed completely.

So I want to write information in the meanwhile


Please do let me help I am new here...

So, what do you want Python to do for you?

I am running the service as a process in python and I am able to read the content of the service but I am able to write the content only when the complete service is run completely, as the service is an iterative process it would take 1 hr to complete but I want to be written it meanwhile the service is running......

Assuming the name of your service is service , you could try to run this program

# runservice.py
import subprocess as sp
import sys
SERVICE_COMMAND = "service"

def run_service(command):
    with open("output.txt", "w") as output_file:
        process = sp.Popen(command, shell=True, stdout=sp.PIPE)
        for line in process.stdout:
            for f in (output_file, sys.stdout):
                f.write(line)
        process.wait()

if __name__ == "__main__":
   run_service(SERVICE_COMMAND)

Warning: 'with' will become a reserved keyword in Python 2.6

I am receiving this warning and nothing is being written in the file

Thank you Mr.Gribouillis

it is really a very helpful stuff for me can you please guide me regarding learning the modules of python and refer me some books if possible..

and please tell me the use of

if __name__ == "__main__":
run_service(SERVICE_COMMAND)

and please tell me the use of

if __name__ == "__main__":
run_service(SERVICE_COMMAND)

This tella python to run the function if the file is run directly and not imported somewhere

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.