A pythonic way to separate the process?

I run a process etcdthat remains active until you kill it. (It does not provide a daemon mode parameter.) I want to separate it so that I can continue to run more python.

What would I do in a shell

etcd & next_cmd

I am using python library shon an enthusiastic recommendation of the whole Internet. I would prefer not to dive into subprocessor Popen, but I also did not find a solution using them.

What I want,

sh.etcd(detach=True)
sh.next_cmd()

or

sh.etcd("&")
sh.next_cmd()

Unfortunately, detachit is not kwarg, but is shconsidered "&"as a flag etcd.

Am I missing something? What a good way to do this?

+4
source share
3 answers

sh &, subprocess:

import subprocess

etcd = subprocess.Popen('etcd') # continue immediately
next_cmd_returncode = subprocess.call('next_cmd') # wait for it
# ... run more python here ...
etcd.terminate() 
etcd.wait()

"" ( Python, python-daemon. , , , supervisord).

+5

, time.sleep(...), etcd , , . , , API, , .

1 ( multiprocessing):

import sh
import requests
import time

from multiprocessing import Process

etcd = Process(target=sh.etcd)

try:
    # start etcd
    etcd.start()
    time.sleep(3)

    # do other stuff
    r = requests.get('http://localhost:4001/v2/keys/')
    print r.text
finally:
    etcd.terminate()

multiprocessing . , etcd.

2 ( ):

import os
import signal
import time
import requests

pid = os.fork()
if pid == 0:
    # start etcd
    os.execvp('etcd', ['etcd'])

try:
    # do other stuff
    time.sleep(3)
    r = requests.get('http://localhost:4001/v2/keys/')
    print r.text
finally:
    os.kill(pid, signal.SIGTERM)

It uses a traditional model forkand execthat works just as well in Python as it does in C. In this model, the output etcd will be displayed on your console, which may or may not be what you want. You can control this by redirecting stdoutand stderrin the child process.

+1
source

All Articles