Changeset b56c76c for protocols


Ignore:
Timestamp:
2013-02-11T12:56:03Z (12 years ago)
Author:
Miklos Vajna <vmiklos@…>
Branches:
master
Children:
7e5b4bd
Parents:
ee3bccd
git-author:
Mike Kazantsev <mk.fraggod@…> (11-02-13 12:56:03)
git-committer:
Miklos Vajna <vmiklos@…> (11-02-13 12:56:03)
Message:

skype: use argparse instead of getopt for CLI in skyped

File:
1 edited

Legend:

Unmodified
Added
Removed
  • protocols/skype/skyped.py

    ree3bccd rb56c76c  
    11#!/usr/bin/env python2.7
    2 # 
     2#
    33#   skyped.py
    4 # 
     4#
    55#   Copyright (c) 2007-2013 by Miklos Vajna <vmiklos@vmiklos.hu>
    66#
     
    99#   the Free Software Foundation; either version 2 of the License, or
    1010#   (at your option) any later version.
    11 # 
     11#
    1212#   This program is distributed in the hope that it will be useful,
    1313#   but WITHOUT ANY WARRANTY; without even the implied warranty of
    1414#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1515#   GNU General Public License for more details.
    16 # 
     16#
    1717#   You should have received a copy of the GNU General Public License
    1818#   along with this program; if not, write to the Free Software
    19 #   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 
     19#   Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
    2020#   USA.
    2121#
     
    2424import os
    2525import signal
    26 import locale
    2726import time
    2827import socket
    29 import getopt
    3028import Skype4Py
    3129import hashlib
     
    281279                sock = open(mock)
    282280                self.lines = sock.readlines()
    283        
     281
    284282        def SendCommand(self, c):
    285283                pass
     
    380378                        dprint("Warning, sending '%s' failed (%s)." % (e, s))
    381379
    382 class Options:
    383         def __init__(self):
    384                 self.cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
    385                 # fall back to system-wide settings
    386                 self.syscfgpath = "/usr/local/etc/skyped/skyped.conf"
    387                 if os.path.exists(self.syscfgpath) and not os.path.exists(self.cfgpath):
    388                         self.cfgpath = self.syscfgpath
    389                 self.daemon = True
    390                 self.debug = False
    391                 self.help = False
    392                 self.host = "0.0.0.0"
    393                 self.log = None
    394                 self.port = None
    395                 self.version = False
    396                 # well, this is a bit hackish. we store the socket of the last connected client
    397                 # here and notify it. maybe later notify all connected clients?
    398                 self.conn = None
    399                 # this will be read first by the input handler
    400                 self.buf = None
    401                 self.mock = None
    402 
    403 
    404         def usage(self, ret):
    405                 print """Usage: skyped [OPTION]...
    406 
    407 skyped is a daemon that acts as a tcp server on top of a Skype instance.
    408 
    409 Options:
    410         -c      --config        path to configuration file (default: %s)
    411         -d      --debug         enable debug messages
    412         -h      --help          this help
    413         -H      --host          set the tcp host, supports IPv4 and IPv6 (default: %s)
    414         -l      --log           set the log file in background mode (default: none)
    415         -n      --nofork        don't run as daemon in the background
    416         -p      --port          set the tcp port (default: %s)
    417         -v      --version       display version information""" % (self.cfgpath, self.host, self.port)
    418                 sys.exit(ret)
    419380
    420381def serverloop(options, skype):
     
    459420                                options.last_bitlbee_pong = now
    460421
    461 if __name__=='__main__':
    462         options = Options()
    463         try:
    464                 opts, args = getopt.getopt(sys.argv[1:], "c:dhH:l:m:np:v", ["config=", "debug", "help", "host=", "log=", "mock=", "nofork", "port=", "version"])
    465         except getopt.GetoptError:
    466                 options.usage(1)
    467         for opt, arg in opts:
    468                 if opt in ("-c", "--config"):
    469                         options.cfgpath = arg
    470                 elif opt in ("-d", "--debug"):
    471                         options.debug = True
    472                 elif opt in ("-h", "--help"):
    473                         options.help = True
    474                 elif opt in ("-H", "--host"):
    475                         options.host = arg
    476                 elif opt in ("-l", "--log"):
    477                         options.log = arg
    478                 elif opt in ("-m", "--mock"):
    479                         options.mock = arg
    480                 elif opt in ("-n", "--nofork"):
    481                         options.daemon = False
    482                 elif opt in ("-p", "--port"):
    483                         options.port = int(arg)
    484                 elif opt in ("-v", "--version"):
    485                         options.version = True
    486         if options.help:
    487                 options.usage(0)
    488         elif options.version:
     422
     423def main(args=None):
     424        global options
     425        global skype
     426
     427        cfgpath = os.path.join(os.environ['HOME'], ".skyped", "skyped.conf")
     428        syscfgpath = "/usr/local/etc/skyped/skyped.conf"
     429        if not os.path.exists(cfgpath) and os.path.exists(syscfgpath):
     430                cfgpath = syscfgpath # fall back to system-wide settings
     431        port = 2727
     432
     433        import argparse
     434        parser = argparse.ArgumentParser()
     435        parser.add_argument('-c', '--config',
     436                metavar='path', default=cfgpath,
     437                help='path to configuration file (default: %(default)s)')
     438        parser.add_argument('-H', '--host', default='0.0.0.0',
     439                help='set the tcp host, supports IPv4 and IPv6 (default: %(default)s)')
     440        parser.add_argument('-p', '--port', type=int,
     441                help='set the tcp port (default: %(default)s)')
     442        parser.add_argument('-l', '--log', metavar='path',
     443                help='set the log file in background mode (default: none)')
     444        parser.add_argument('-v', '--version', action='store_true', help='display version information')
     445        parser.add_argument('-n', '--nofork',
     446                action='store_true', help="don't run as daemon in the background")
     447        parser.add_argument('-m', '--mock', help='fake interactions with skype (only useful for tests)')
     448        parser.add_argument('-d', '--debug', action='store_true', help='enable debug messages')
     449        options = parser.parse_args(sys.argv[1:] if args is None else args)
     450
     451        if options.version:
    489452                print "skyped %s" % __version__
    490453                sys.exit(0)
    491         # parse our config
    492         if not os.path.exists(options.cfgpath):
    493                 print "Can't find configuration file at '%s'." % options.cfgpath
    494                 print "Use the -c option to specify an alternate one."
    495                 sys.exit(1)
     454
     455        # well, this is a bit hackish. we store the socket of the last connected client
     456        # here and notify it. maybe later notify all connected clients?
     457        options.conn = None
     458        # this will be read first by the input handler
     459        options.buf = None
     460
     461        if not os.path.exists(options.config):
     462                parser.error(( "Can't find configuration file at '%s'."
     463                        "Use the -c option to specify an alternate one." )% options.config)
     464
     465        cfgpath = options.config
    496466        options.config = ConfigParser()
    497         options.config.read(options.cfgpath)
    498         options.config.username = options.config.get('skyped', 'username').split('#')[0]
    499         options.config.password = options.config.get('skyped', 'password').split('#')[0]
    500         options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#')[0])
    501         options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#')[0])
     467        options.config.read(cfgpath)
     468        options.config.username = options.config.get('skyped', 'username').split('#', 1)[0]
     469        options.config.password = options.config.get('skyped', 'password').split('#', 1)[0]
     470        options.config.sslkey = os.path.expanduser(options.config.get('skyped', 'key').split('#', 1)[0])
     471        options.config.sslcert = os.path.expanduser(options.config.get('skyped', 'cert').split('#', 1)[0])
     472
    502473        # hack: we have to parse the parameters first to locate the
    503474        # config file but the -p option should overwrite the value from
    504475        # the config file
    505476        try:
    506                 options.config.port = int(options.config.get('skyped', 'port').split('#')[0])
     477                options.config.port = int(options.config.get('skyped', 'port').split('#', 1)[0])
    507478                if not options.port:
    508479                        options.port = options.config.port
     
    510481                pass
    511482        if not options.port:
    512                 options.port = 2727
    513         dprint("Parsing config file '%s' done, username is '%s'." % (options.cfgpath, options.config.username))
    514         if options.daemon:
     483                options.port = port
     484        dprint("Parsing config file '%s' done, username is '%s'." % (options.config, options.config.username))
     485        if not options.nofork:
    515486                pid = os.fork()
    516487                if pid == 0:
     
    540511                        options.lock = threading.Lock()
    541512                        server(options.host, options.port, skype)
     513
     514
     515if __name__ == '__main__': main()
Note: See TracChangeset for help on using the changeset viewer.