0

I try to make a backup script in python and start, stop a service with popen... Stopping the service is working, but unfortunatly starting the service works, but blocks the rest of the execution, the scripts stays there, why ?

Seems to be somehow linked with the httpd service... :-(

the program config element is like "service;httpd;start" or "/etc/init.d/myprog;start"

class execute(actions):
    def __init__(self,config,section,logger):
        self.name="execute"
        actions.__init__(self,config,section,logger)

    def process(self):
        try:
            program=self.config.get(self.section,"program").split(";")
            self.logger.debug("program=%s" % program)
            p = subprocess.Popen(program, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            stdout, stderr = p.communicate()

            if stdout:
                self.logger.info(stdout)
            if stderr:
                self.logger.error(stderr)

            return p.returncode

        except Exception:
            self.logger.exception(Exception)
3
  • Hmm, what happens when you type service myprog start in command line? Would you have to wait until you type service myprog stop in another terminal? Aug 12, 2015 at 14:36
  • no that goes pretty quick, about 5 secs
    – OpenStove
    Aug 21, 2015 at 14:02
  • I'm also wondering why stdout is only shown when command ends... I don't see it while running
    – OpenStove
    Aug 21, 2015 at 14:19

2 Answers 2

2

You have to open a stdin as a pipe as well, and then close it (if you use read() and write() instead of communicate()).

p = subprocess.Popen(..., stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.close()
print "Stdout:", p.stdout.read()
print "Stderr:", p.stderr.read()

If it doesn't work, and you don't really need any checks, just close all pipes after call to Popen, what will cause program execution and detachment from pipes.

Warning: This will make program run as a daemon if it doesn't terminate on its own.

After doing this you may call wait() to see whether it'll block as well. And use exitcodes to check for eventual errors.

There are not much of them. Just service started or not. Sometimes even it returns that service is running, but service crashes.

To check whether service script is still running, but without blocking, use:

if p.poll()==None: print "Still running"

Else, poll() returns the exit code.

This works neatly for starting and stopping a service:

from subprocess import Popen, PIPE
service = "brltty"
p = Popen(["service", service, "start"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
# Note: using sequence uses shell=0
stdout, stderr = p.communicate()
print "Stdout:", stdout
print "Stderr:", stderr

Don't forget to change start to stop :D :D :D

8
  • In Fact I'm trying to stop and start and normal linux service... Starting needs about 30 seconds, stopping about 15... But the scripts doesn't finish even after 10 Minutes, when everything is already running again since a while... If I running without pipes, I didn't know if the command went well, or if there was an erro
    – OpenStove
    Aug 12, 2015 at 14:00
  • Yes, I saw what you tried. Don't use communicate() if you really have to dig through pipes. Use p.stdout.read() or p.stderr.read(). And as I said, you wouldn't be able to deduce much, and even won't receive any errors regardless they're there. The extra problem is that the service script starts the service as well. So it is the script that calls a daemon. Sometimes it may confuse things. Do what I say, it works!
    – Dalen
    Aug 12, 2015 at 14:08
  • Sorry, closing stdin before communicate() causes an IO error. I forgot. But stopping works without closing anything, with communicate but when stdin is opened as a PIPE as well.
    – Dalen
    Aug 12, 2015 at 14:18
  • What's the difference between you last peace of code and mine ? I'm not sure to understand ?
    – OpenStove
    Aug 19, 2015 at 15:46
  • That it has stdin=PIPE. As I wrote in first line of the answer. That causes communicate() to close the stdin after calling it. That in turn ensures that the program is terminated. Without it, it seems, service script for some reason blocks. This works for me, does it work in your case?
    – Dalen
    Aug 19, 2015 at 20:41
0

The call to p.communicate() waits for the process to terminate.

Refer to: subprocess documentation

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

You can try to use p.poll() instead. This method doesn't wait for a process to terminate.

3
  • I still don't undestand why service myprog stop is working, and service myprog start not ? Why is the process not terminating ?
    – OpenStove
    Aug 12, 2015 at 13:31
  • I'm missing actual commands which are invoked upon start/stop. My guess is that stop terminates the services and returns immediately, thus you are not observing waiting on p.communicate in this case. However service start invokes a long running activity and p.communicate waits for this activity to complete. Aug 12, 2015 at 13:36
  • No thats my problem the "service xxx start" process is during about a few seconds, but p.communicate stays stucked... I don't explain me why
    – OpenStove
    Aug 19, 2015 at 15:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.