How to run twisted script as daemon without twistd command

Warning:- this article assumes you are familiar with twisted
we have scenarios like run different services on different ports
to create multiservice architecture.
So, here we cannot run the services on from the command line
we have to run them as daemon service, like using cron jobs in linux.

– Create a simple twisted with protocol and factory and save to or any name you like.

#!/usr/bin/env python2.7

from twisted.internet import protocol, reactor

class echo(protocol.Protocol):
        def dataReceived(self, data):

class echoFactory(protocol.Factory):
        def buildProtocol(sef,addr):
                print 'called'
                return echo()


this is a normal echo server script which can run using

./ # assuming the script is saved in

But our script cannot run this is as a daemon service
daemon service is some task runs in the background, and it logs to some specific location, not on stdout. When we run this script like specified above, it blocks the current terminal ( if you are running from a terminal ) which is not something daemon script do.
To make this script run as a daemon, we need to use twistd inside the script
means it’ll run and execute, create a process in the background.

from twisted.scripts import twistd
import sys
sys.argv.append('-y dummy')
sys.argv.append('--pidfile={0} --logfile=/dev/null'.format('/tmp/'))

application = service.Application('echo_daemon')
tcp_service = internet.TCPServer(interface='',port=8000, factory=factory)

class ApplicationRunner(twistd._SomeApplicationRunner):
    def createOrGetApplication(self):
        return application

    def run(self):
        self.application = self.createOrGetApplication()

twistd._SomeApplicationRunner = ApplicationRunner

#~ python2.7

How should we cross-check if the service is running or not
Use the following command on Linux system (in shell/terminal for simple word).

netstat -ntulp

You get a list of all ports (UDP, TCP) open on the system.

Leave a Reply

Your email address will not be published. Required fields are marked *