Best Python code snippet using fMBT_python
pythonshare-client
Source:pythonshare-client  
1#!/usr/bin/env python22# fMBT, free Model Based Testing tool3# Copyright (c) 2013, Intel Corporation.4#5# Author: antti.kervinen@intel.com6#7# This program is free software; you can redistribute it and/or modify it8# under the terms and conditions of the GNU Lesser General Public License,9# version 2.1, as published by the Free Software Foundation.10#11# This program is distributed in the hope it will be useful, but WITHOUT12# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or13# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for14# more details.15#16# You should have received a copy of the GNU Lesser General Public License along with17# this program; if not, write to the Free Software Foundation, Inc.,18# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.19# This executable implements a commandline interface for executing20# Python code on pythonshare servers.21"""Pythonshare client - connect to shared distributed namespaces22Usage: pythonshare-client [options]23Options:24  -h, --help25          Print this help.26  -C, --connect=hostspec27          Connect to pythonshare-server at hostspec. Options28          when connected will be executed on this connection.29  -n, --namespace=ns30          Set namespace to be used in for code/eval/interact/drop.31  -A, --async32          Following python-code executions and evaluations33          will be asynchronous.34  -S, --sync35          Following python-code executions and evaluations36          will be synchronous. This is the default.37  -o, --output=filename38          Output from following successful python-code evaluations39          will be written to filename. The default is standard output.40  -f, --format=format41          Evaluation return values will be converted to string with42          given formatter. Valid options are str, repr, pickle, print43          and raw.44  --password=password45          Authenticate to pythonshare server with password. The password46          must be plain text.47  --password-file=filename48          Authenticate to pythonshare server with password from49          filename. The password must be in filename in plain text.50Options when connected:51  -c, --code=python-code52          Execute python-code in ns.53  -e, --eval=python-expression54          Evaluate python-expression in ns. Print return55          value to standard output.56  -i, --interact57          Open interactive console for running code in ns.58  --ls-local59          List local namespaces.60  --ls-remote61          List remote namespaces.62  --ls-remote-ip63          List remote namespaces with namespace registerer's IP64          address and port.65  --ns-type=ns66          Returns type of a namespace ("local", "remote" or "" if it67          does not exist).68  --drop69          Drop namespace ns from the server.70  --unlock71          Unlock locked ns on the server.72  -D, --disconnect73          Disconnect from the pythonshare-server.74  -k, --kill75          Shutdown pythonshare-server.76  -P, --poll77          Poll which asynchronously return values are available for78          reading.79  -r, --read ASYNC_RV80          Read an asynchronous return value.81Example:82  pythonshare-client -C socket://localhost:8089 -n myns -c 'a=41' -e 'a+1'83"""84import pythonshare85import code86import cPickle87import getopt88import parser89import sys90import traceback91opt_output_file = sys.stdout92def error(msg, exit_status=1):93    sys.stderr.write("pythonshare-client: %s\n" % (msg,))94    sys.exit(1)95def output(data):96    opt_output_file.write(data)97    opt_output_file.flush()98formatter_str    = lambda o: str(o)99formatter_repr   = lambda o: repr(o)100formatter_raw    = lambda o: o101formatter_pickle = lambda o: cPickle.dumps(o)102formatter_print  = lambda o: str(o) + "\n"103def _pythonCode(code):104    try:105        parser.expr(code)106        return "expression"107    except SyntaxError:108        try:109            parser.suite(code.encode("utf8"))110            return "suite"111        except SyntaxError:112            return None113class PythonshareConsole(code.InteractiveConsole):114    def __init__(self, *args, **kwargs):115        try:116            import readline117        except:118            pass119        self._conn = kwargs.pop("conn")120        self._ns = kwargs.pop("namespace", None)121        if self._ns == None:122            self._ns = conn.namespace()123        code.InteractiveConsole.__init__(self, *args, **kwargs)124        self.__class__.__name__ = "pythonshare namespace %s at %s" % (125            self._ns, getattr(self._conn, "hostspec", "N/A"))126        self._codelines = ""127    def runsource(self, source, *args):128        self._codelines = source129        try:130            need_more = code.InteractiveConsole.runsource(self, source, *args)131        except:132            self._codelines = ""133            raise134        return need_more135    def runcode(self, code):136        source = self._codelines137        self._codelines = ""138        code_type = _pythonCode(source)139        try:140            if code_type == "expression":141                print self._conn.eval_in(self._ns, source)142            elif code_type == "suite":143                self._conn.exec_in(self._ns, source)144            else:145                return146        except pythonshare.PythonShareError, e:147            tb_lines = traceback.format_exc().splitlines()148            try:149                i = tb_lines.index("RemoteEvalError: Traceback (most recent call last):")150                print tb_lines[i]151            except ValueError:152                try:153                    i = tb_lines.index("RemoteExecError: Traceback (most recent call last):")154                    print tb_lines[i]155                except ValueError:156                    print "i=-2"157                    i = -2158            print "\n".join(tb_lines[i+3:])159    def showsyntaxerror(self, *args):160        self._codelines = ""161        return code.InteractiveConsole.showsyntaxerror(self, *args)162if __name__ == "__main__":163    try:164        opts, remainder = getopt.gnu_getopt(165            sys.argv[1:], "C:DAhSs:Pp:n:c:e:r:o:f:ik",166            ["connect=", "disconnect",167             "async", "sync", "poll",168             "help", "server=", "port=",169             "password=", "password-file=",170             "namespace=", "code=", "eval=", "read=",171             "output=", "format=", "interact",172             "ls-local", "ls-remote", "ls-remote-ip", "ns-type=",173             "drop", "unlock", "kill"])174    except getopt.GetoptError, e:175        error(str(e))176    opt_server = "localhost"177    opt_port = pythonshare.default_port178    opt_namespace = None179    opt_async = False180    opt_formatter = formatter_str181    opt_password = None182    conn = None183    if len(remainder) > 0:184        error('unknown parameter(s): "%s"' %185              '", "'.join(remainder))186    for opt, arg in opts:187        if opt in ["-h", "--help"]:188            print __doc__189            sys.exit(0)190        elif opt in ["-s", "--server"]:191            opt_server = arg192        elif opt in ["-p", "--port"]:193            try:194                opt_port = int(arg)195            except ValueError:196                error('invalid port "%s", integer expected.' % (arg,))197        elif opt in ["--password"]:198            opt_password = arg199        elif opt in ["--password-file"]:200            try:201                opt_password = file(arg).read().strip()202            except IOError as err:203                error('error reading password file "%s": %s' % (arg, err))204        elif opt in ["-C", "--connect"]:205            hostspec = arg206            try:207                conn = pythonshare.connection(hostspec, password=opt_password)208            except pythonshare.socket.error, e:209                error('cannot connect to "%s": %s' % (hostspec, e))210        elif opt in ["-D", "--disconnect"]:211            conn.close()212            conn = None213        elif opt in ["-n", "--namespace"]:214            opt_namespace = arg215            if conn:216                conn.set_namespace(opt_namespace)217        elif opt in ["-c", "--code"]:218            if conn == None:219                conn = pythonshare.connection("socket://%s:%s" %220                                              (opt_server, opt_port),221                                              password=opt_password)222            try:223                if opt_namespace:224                    conn.set_namespace(opt_namespace)225                conn.exec_(arg, async=opt_async)226            except pythonshare.PythonShareError, e:227                print type(e)228                print e229        elif opt in ["-e", "--eval"]:230            if conn == None:231                conn = pythonshare.connection("socket://%s:%s" %232                                              (opt_server, opt_port),233                                              password=opt_password)234            try:235                if opt_namespace:236                    conn.set_namespace(opt_namespace)237                output(opt_formatter(238                    conn.eval_(arg, async=opt_async)))239            except pythonshare.PythonShareError, e:240                print type(e)241                print e242        elif opt in ["-i", "--interact"]:243            if conn == None:244                conn = pythonshare.connection("socket://%s:%s" %245                                              (opt_server, opt_port),246                                              password=opt_password)247            console = PythonshareConsole(conn=conn, namespace=opt_namespace)248            console.interact()249        elif opt in ["--ls-local"]:250            if conn == None:251                error("cannot list namespaces - not connected")252            try:253                local_nss = conn.ls_local()254            except Exception, e:255                error('cannot list local namespaces: %s' % (e,))256            print "\n".join(local_nss)257        elif opt in ["--ls-remote"]:258            if conn == None:259                error("cannot list namespaces - not connected")260            try:261                remote_nss = conn.ls_remote()262            except Exception, e:263                error('cannot list remote namespaces: %s' % (e,))264            print "\n".join(remote_nss)265        elif opt in ["--ls-remote-ip"]:266            if conn == None:267                error("cannot list namespaces - not connected")268            try:269                remote_nss = conn.ls_remote(ip=True)270            except Exception, e:271                error('cannot list remote namespaces and addresses: %s' % (e,))272            for name in sorted(remote_nss.keys()):273                print name, remote_nss[name][0], remote_nss[name][1]274        elif opt in ["--ns-type"]:275            if conn == None:276                error("cannot query namespace - not connected")277            try:278                ns_type = conn.ns_type(arg)279            except Exception, e:280                error('cannot get namespaces type: %s' % (e,))281            if ns_type != None:282                print ns_type283        elif opt in ["--drop"]:284            if conn == None:285                error("cannot drop namespace - not connected")286            if not opt_namespace:287                opt_namespace = conn.namespace()288            try:289                conn.drop_ns(opt_namespace)290            except Exception, e:291                error("cannot drop namespace: %s" % (292                    str(e).strip().splitlines()[-1].split(":")[-1].strip(),))293        elif opt in ["--unlock"]:294            if conn == None:295                error("cannot unlock namespace - not connected")296            if not opt_namespace:297                opt_namespace = conn.namespace()298            try:299                conn.unlock_ns(opt_namespace)300            except Exception, e:301                error("cannot unlock namespace: %s" % (302                    str(e).strip().splitlines()[-1].split(":")[-1].strip(),))303        elif opt in ["-k", "--kill"]:304            if conn == None:305                error("cannot kill server - not connected")306            if not opt_namespace:307                opt_namespace = conn.namespace()308            try:309                conn.kill_server(opt_namespace)310            except Exception, e:311                error("error on kill: %s" % (e,))312        elif opt in ["-r", "--read"]:313            try:314                try:315                    if not opt_namespace:316                        opt_namespace = conn.namespace()317                    index = int(arg)318                    # arg is an index to the list of poll_rvs319                    l = conn.poll_rvs(opt_namespace)320                    print conn.read_rv(l[index])321                except ValueError: # arg is a Async_rv string322                    print conn.read_rv(arg)323            except pythonshare.PythonShareError, e:324                print type(e)325                print e326        elif opt in ["-A", "--async"]:327            opt_async = True328        elif opt in ["-S", "--sync"]:329            opt_async = False330        elif opt in ["-P", "--poll"]:331            if not opt_namespace:332                opt_namespace = conn.namespace()333            async_rvs = conn.poll_rvs(opt_namespace)334            print "\n".join([str(arv) for arv in async_rvs])335        elif opt in ["-o", "--output"]:336            opt_output_file = file(arg, "w")337        elif opt in ["-f", "--format"]:338            try:339                opt_formatter = globals()["formatter_%s" % (arg,)]340            except KeyError:...python3share-client
Source:python3share-client  
1#!/usr/bin/env python32# fMBT, free Model Based Testing tool3# Copyright (c) 2013-2019, Intel Corporation.4#5# Author: antti.kervinen@intel.com6#7# This program is free software; you can redistribute it and/or modify it8# under the terms and conditions of the GNU Lesser General Public License,9# version 2.1, as published by the Free Software Foundation.10#11# This program is distributed in the hope it will be useful, but WITHOUT12# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or13# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for14# more details.15#16# You should have received a copy of the GNU Lesser General Public License along with17# this program; if not, write to the Free Software Foundation, Inc.,18# 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.19# This executable implements a commandline interface for executing20# Python code on pythonshare servers.21"""Pythonshare client - connect to shared distributed namespaces22Usage: pythonshare-client [options]23Options:24  -h, --help25          Print this help.26  -C, --connect=hostspec27          Connect to pythonshare-server at hostspec. Options28          when connected will be executed on this connection.29  -n, --namespace=ns30          Set namespace to be used in for code/eval/interact/drop.31  -A, --async32          Following python-code executions and evaluations33          will be asynchronous.34  -S, --sync35          Following python-code executions and evaluations36          will be synchronous. This is the default.37  -o, --output=filename38          Output from following successful python-code evaluations39          will be written to filename. The default is standard output.40  -f, --format=format41          Evaluation return values will be converted to string with42          given formatter. Valid options are str, repr, pickle, print43          and raw.44  --password=password45          Authenticate to pythonshare server with password. The password46          must be plain text.47  --password-file=filename48          Authenticate to pythonshare server with password from49          filename. The password must be in filename in plain text.50Options when connected:51  -c, --code=python-code52          Execute python-code in ns.53  -e, --eval=python-expression54          Evaluate python-expression in ns. Print return55          value to standard output.56  -i, --interact57          Open interactive console for running code in ns.58  --ls-local59          List local namespaces.60  --ls-remote61          List remote namespaces.62  --ls-remote-ip63          List remote namespaces with namespace registerer's IP64          address and port.65  --ns-type=ns66          Returns type of a namespace ("local", "remote" or "" if it67          does not exist).68  --drop69          Drop namespace ns from the server.70  --unlock71          Unlock locked ns on the server.72  -D, --disconnect73          Disconnect from the pythonshare-server.74  -k, --kill75          Shutdown pythonshare-server.76  -P, --poll77          Poll which asynchronously return values are available for78          reading.79Example:80  pythonshare-client -C socket://localhost:8089 -n myns -c 'a=41' -e 'a+1'81"""82import python3share83import code84import pickle85import getopt86import parser87import sys88import traceback89opt_output_file = sys.stdout90def error(msg, exit_status=1):91    sys.stderr.write("pythonshare-client: %s\n" % (msg,))92    sys.exit(1)93def output(data):94    opt_output_file.write(data)95    opt_output_file.flush()96formatter_str    = lambda o: str(o)97formatter_repr   = lambda o: repr(o)98formatter_raw    = lambda o: o99formatter_pickle = lambda o: pickle.dumps(o)100formatter_print  = lambda o: str(o) + "\n"101def _pythonCode(code):102    try:103        parser.expr(code)104        return "expression"105    except SyntaxError:106        try:107            parser.suite(code.encode("utf8"))108            return "suite"109        except SyntaxError:110            return None111class PythonshareConsole(code.InteractiveConsole):112    def __init__(self, *args, **kwargs):113        try:114            import readline115        except:116            pass117        self._conn = kwargs.pop("conn")118        self._ns = kwargs.pop("namespace", None)119        if self._ns == None:120            self._ns = conn.namespace()121        code.InteractiveConsole.__init__(self, *args, **kwargs)122        self.__class__.__name__ = "pythonshare namespace %s at %s" % (123            self._ns, getattr(self._conn, "hostspec", "N/A"))124        self._codelines = ""125    def runsource(self, source, *args):126        self._codelines = source127        try:128            need_more = code.InteractiveConsole.runsource(self, source, *args)129        except:130            self._codelines = ""131            raise132        return need_more133    def runcode(self, code):134        source = self._codelines135        self._codelines = ""136        code_type = _pythonCode(source)137        try:138            if code_type == "expression":139                print(self._conn.eval_in(self._ns, source))140            elif code_type == "suite":141                self._conn.exec_in(self._ns, source)142            else:143                return144        except python3share.PythonShareError as e:145            tb_lines = traceback.format_exc().splitlines()146            try:147                i = tb_lines.index("RemoteEvalError: Traceback (most recent call last):")148                print(tb_lines[i])149            except ValueError:150                try:151                    i = tb_lines.index("RemoteExecError: Traceback (most recent call last):")152                    print(tb_lines[i])153                except ValueError:154                    print("i=-2")155                    i = -2156            print("\n".join(tb_lines[i+3:]))157    def showsyntaxerror(self, *args):158        self._codelines = ""159        return code.InteractiveConsole.showsyntaxerror(self, *args)160if __name__ == "__main__":161    try:162        opts, remainder = getopt.gnu_getopt(163            sys.argv[1:], "C:DAhSs:Pp:n:c:e:r:o:f:ik",164            ["connect=", "disconnect",165             "async", "sync", "poll",166             "help", "server=", "port=",167             "password=", "password-file=",168             "namespace=", "code=", "eval=", "read=",169             "output=", "format=", "interact",170             "ls-local", "ls-remote", "ls-remote-ip", "ns-type=",171             "drop", "unlock", "kill"])172    except getopt.GetoptError as e:173        error(str(e))174    opt_server = "localhost"175    opt_port = python3share.default_port176    opt_namespace = None177    opt_async = False178    opt_formatter = formatter_str179    opt_password = None180    conn = None181    if len(remainder) > 0:182        error('unknown parameter(s): "%s"' %183              '", "'.join(remainder))184    for opt, arg in opts:185        if opt in ["-h", "--help"]:186            print(__doc__)187            sys.exit(0)188        elif opt in ["-s", "--server"]:189            opt_server = arg190        elif opt in ["-p", "--port"]:191            try:192                opt_port = int(arg)193            except ValueError:194                error('invalid port "%s", integer expected.' % (arg,))195        elif opt in ["--password"]:196            opt_password = arg197        elif opt in ["--password-file"]:198            try:199                opt_password = file(arg).read().strip()200            except IOError as err:201                error('error reading password file "%s": %s' % (arg, err))202        elif opt in ["-C", "--connect"]:203            hostspec = arg204            try:205                conn = python3share.connection(hostspec, password=opt_password)206            except python3share.socket.error as e:207                error('cannot connect to "%s": %s' % (hostspec, e))208        elif opt in ["-D", "--disconnect"]:209            conn.close()210            conn = None211        elif opt in ["-n", "--namespace"]:212            opt_namespace = arg213            if conn:214                conn.set_namespace(opt_namespace)215        elif opt in ["-c", "--code"]:216            if conn == None:217                conn = python3share.connection("socket://%s:%s" %218                                              (opt_server, opt_port),219                                              password=opt_password)220            try:221                if opt_namespace:222                    conn.set_namespace(opt_namespace)223                conn.exec_(arg, async_=opt_async)224            except python3share.PythonShareError as e:225                print(type(e))226                print(e)227        elif opt in ["-e", "--eval"]:228            if conn == None:229                conn = python3share.connection("socket://%s:%s" %230                                              (opt_server, opt_port),231                                              password=opt_password)232            try:233                if opt_namespace:234                    conn.set_namespace(opt_namespace)235                output(opt_formatter(236                    conn.eval_(arg, async_=opt_async)))237            except python3share.PythonShareError as e:238                print(type(e))239                print(e)240        elif opt in ["-i", "--interact"]:241            if conn == None:242                conn = python3share.connection("socket://%s:%s" %243                                              (opt_server, opt_port),244                                              password=opt_password)245            console = PythonshareConsole(conn=conn, namespace=opt_namespace)246            console.interact()247        elif opt in ["--ls-local"]:248            if conn == None:249                error("cannot list namespaces - not connected")250            local_nss = conn.ls_local()251            print("\n".join(local_nss))252        elif opt in ["--ls-remote"]:253            if conn == None:254                error("cannot list namespaces - not connected")255            remote_nss = conn.ls_remote()256            print("\n".join(remote_nss))257        elif opt in ["--ls-remote-ip"]:258            if conn == None:259                error("cannot list namespaces - not connected")260            remote_nss = conn.ls_remote(ip=True)261            for name in sorted(remote_nss.keys()):262                print(name, remote_nss[name][0], remote_nss[name][1])263        elif opt in ["--ns-type"]:264            if conn == None:265                error("cannot query namespace - not connected")266            ns_type = conn.ns_type(arg)267            if ns_type != None:268                print(ns_type)269        elif opt in ["--drop"]:270            if conn == None:271                error("cannot drop namespace - not connected")272            if not opt_namespace:273                opt_namespace = conn.namespace()274            try:275                conn.drop_ns(opt_namespace)276            except Exception as e:277                error("cannot drop namespace: %s" % (278                    str(e).strip().splitlines()[-1].split(":")[-1].strip(),))279        elif opt in ["--unlock"]:280            if conn == None:281                error("cannot unlock namespace - not connected")282            if not opt_namespace:283                opt_namespace = conn.namespace()284            try:285                conn.unlock_ns(opt_namespace)286            except Exception as e:287                error("cannot unlock namespace: %s" % (288                    str(e).strip().splitlines()[-1].split(":")[-1].strip(),))289        elif opt in ["-k", "--kill"]:290            if conn == None:291                error("cannot kill server - not connected")292            if not opt_namespace:293                opt_namespace = conn.namespace()294            try:295                conn.kill_server(opt_namespace)296            except Exception as e:297                error("error on kill: %s" % (e,))298        elif opt in ["-r", "--read"]:299            try:300                try:301                    if not opt_namespace:302                        opt_namespace = conn.namespace()303                    index = int(arg)304                    # arg is an index to the list of poll_rvs305                    l = conn.poll_rvs(opt_namespace)306                    print(conn.read_rv(l[index]))307                except ValueError: # arg is a Async_rv string308                    print(conn.read_rv(arg))309            except python3share.PythonShareError as e:310                print(type(e))311                print(e)312        elif opt in ["-A", "--async"]:313            opt_async = True314        elif opt in ["-S", "--sync"]:315            opt_async = False316        elif opt in ["-P", "--poll"]:317            if not opt_namespace:318                opt_namespace = conn.namespace()319            async_rvs = conn.poll_rvs(opt_namespace)320            print("\n".join([str(arv) for arv in async_rvs]))321        elif opt in ["-o", "--output"]:322            opt_output_file = file(arg, "w")323        elif opt in ["-f", "--format"]:324            try:325                opt_formatter = globals()["formatter_%s" % (arg,)]326            except KeyError:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
