• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python ptvsd.enable_attach函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中ptvsd.enable_attach函数的典型用法代码示例。如果您正苦于以下问题:Python enable_attach函数的具体用法?Python enable_attach怎么用?Python enable_attach使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了enable_attach函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

    def __init__(self, vscode_debug_secret=None,
                 vscode_debug_address=None, vscode_debug_port=None, **kwargs):
        if vscode_debug_secret is not None:
            ptvsd.enable_attach(
                vscode_debug_secret,
                address=(vscode_debug_address, int(vscode_debug_port))
            )
            print "Waiting for VS Code to attach"
            ptvsd.wait_for_attach()

        if kwargs["gecko_log"] is None:
            kwargs["gecko_log"] = ("logs/marionette.{}.gecko.log"
                                   ).format(int(time.time()))
        self.gecko_log_relpath = kwargs["gecko_log"]

        FirefoxUITestRunner.__init__(self, **kwargs)

        def gather_debug(test, status):
            rv = {}
            marionette = test._marionette_weakref()

            if marionette.session is not None:
                try:
                    self._add_logging_info(rv, marionette)
                except Exception:
                    logger = get_default_logger()
                    logger.warning("Failed to gather test failure debug.",
                                   exc_info=True)
            return rv

        self.result_callbacks.append(gather_debug)
开发者ID:beriain,项目名称:requestpolicy,代码行数:31,代码来源:runner.py


示例2: init_logging

def init_logging(params):
    # Global configuration
    log_file = params.get('logFile', None)
    log_level = params.get('logLevel', logging.ERROR)
    logging.basicConfig(level=log_level, filename=log_file, datefmt='%H:%M:%S',
                        format='[%(asctime)s %(name)s] %(message)s')
    # Individuial loggers
    loggers = params.get('loggers')
    if loggers:
        for name, level in loggers.items():
            logging.getLogger(name).setLevel(level)
    # Visual Studio debug server
    ptvsd_params = params.get('ptvsd')
    if ptvsd_params:
        try:
            import ptvsd
            secret = ptvsd_params.get('secret')
            address = ptvsd_params.get('address', '127.0.0.1')
            port = ptvsd_params.get('port', 3000)
            ptvsd.enable_attach(secret, address = (address, port))
            wait_for = ptvsd_params.get('waitFor')
            if wait_for is not None:
                ptvsd.wait_for_attach(wait_for if wait_for > 0 else None)
        except Exception as e:
            log.error('ptvsd setup failed: %s', e)
开发者ID:harikrishnan94,项目名称:vscode-lldb,代码行数:25,代码来源:main.py


示例3: main

def main():
    """Setup debugging if required and send remaining arguments to execution_function"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--remoteDebug", help="Imports and launches remote debugger")
    parser.add_argument("--vsDelay", type=int, default=200, help="Fixes how long \
  the debugger will wait")
    parser.add_argument("--eclipseHost", help="The host for the thread to be debugged\
    (the client, in practice)")
    test_args, function_args = parser.parse_known_args()

    if str(test_args.remoteDebug).lower() == "vs":
        import ptvsd
        ptvsd.enable_attach(secret="cerro")
        ptvsd.wait_for_attach(test_args.vsDelay)
    elif str(test_args.remoteDebug).lower == "eclipse" and str(test_args.eclipseHost):
        # TODO: Put sanitisation or error-trapping in here for eclipse host and
        # call pydevd
        pass
    funcDict = {}
    # Making a dictionary of the non-test setup arguments not listed above
    for element in function_args:
        k, v = element.split('=', 1)
        funcDict[k.lstrip('--')] = v
    retVal=osd.execute_function(osd.generate_connection(), **funcDict)
    print (str(retVal))
开发者ID:CCATObservatory,项目名称:swdm-osd,代码行数:26,代码来源:debug_osd_api.py


示例4: wait_for_debugger

def wait_for_debugger(timeout=None):
    try:
        ptvsd.enable_attach(secret=None)   
    except:
        pass
    ptvsd.wait_for_attach(timeout)
    return
开发者ID:gtkfi,项目名称:ArcSDM,代码行数:7,代码来源:debug_ptvs.py


示例5: debug

    async def debug(self, engine, options):
        """
        Setup middlewared for remote debugging.

        engines:
          - PTVS: Python Visual Studio
          - PYDEV: Python Dev (Eclipse/PyCharm)

        options:
          - secret: password for PTVS
          - host: required for PYDEV, hostname of local computer (developer workstation)
          - local_path: required for PYDEV, path for middlewared source in local computer (e.g. /home/user/freenas/src/middlewared/middlewared
        """
        if engine == 'PTVS':
            import ptvsd
            if 'secret' not in options:
                raise ValidationError('secret', 'secret is required for PTVS')
            ptvsd.enable_attach(
                options['secret'],
                address=(options['bind_address'], options['bind_port']),
            )
            if options['wait_attach']:
                ptvsd.wait_for_attach()
        elif engine == 'PYDEV':
            for i in ('host', 'local_path'):
                if i not in options:
                    raise ValidationError(i, f'{i} is required for PYDEV')
            os.environ['PATHS_FROM_ECLIPSE_TO_PYTHON'] = json.dumps([
                [options['local_path'], '/usr/local/lib/python3.6/site-packages/middlewared'],
            ])
            import pydevd
            pydevd.stoptrace()
            pydevd.settrace(host=options['host'])
开发者ID:razzfazz,项目名称:freenas,代码行数:33,代码来源:service.py


示例6: debug_remote

def debug_remote(
    file, 
    port_num,
    debug_id,
    wait_on_exception,
    redirect_output, 
    wait_on_exit,
    break_on_systemexit_zero,
    debug_stdlib,
    run_as
):
    global BREAK_ON_SYSTEMEXIT_ZERO, DEBUG_STDLIB
    BREAK_ON_SYSTEMEXIT_ZERO = break_on_systemexit_zero
    DEBUG_STDLIB = debug_stdlib

    import datetime
    print('%s: Remote launcher starting ptvsd attach wait with File: %s, Port: %d, Id: %s\n' % (datetime.datetime.now(), file, port_num, debug_id))

    ptvsd.enable_attach(debug_id, address = ('0.0.0.0', port_num), redirect_output = redirect_output)
    try:
        import _ptvsdhelper
        if _ptvsdhelper.ping_debugger_for_attach():
            ptvsd.wait_for_attach()
    except ImportError:
        _ptvsdhelper = None

    # now execute main file
    globals_obj = {'__name__': '__main__'}
    if run_as == 'module':
        vspd.exec_module(file, globals_obj)
    elif run_as == 'code':
        vspd.exec_code(file, '<string>', globals_obj)
    else:
        vspd.exec_file(file, globals_obj)
开发者ID:BMBurstein,项目名称:PTVS,代码行数:34,代码来源:visualstudio_py_remote_launcher.py


示例7: _enable_ptvsd

def _enable_ptvsd(debuggger_host, debugger_port):
    import ptvsd

    # Allow other computers to attach to ptvsd at this IP address and port.
    ptvsd.enable_attach(address=(debuggger_host, debugger_port),
                        redirect_output=True)

    # Pause the program until a remote debugger is attached
    ptvsd.wait_for_attach()
开发者ID:openstack,项目名称:octavia,代码行数:9,代码来源:config.py


示例8: debuggable_app

def debuggable_app():
    """ For launching with gunicorn from a Heroku Procfile. 
    Problem: both the web and worker processes run the same create_app code. If we start a ptvsd service in create_app, it will be
    started twice on the same port, and fail. 
    Solution: gunicorn gets its app object through this method that also starts the debug server. 
    """
    if settings.DEBUG:
        import ptvsd
        ptvsd.enable_attach(address=('0.0.0.0', 3000))

    return app
开发者ID:formspree,项目名称:formspree,代码行数:11,代码来源:__init__.py


示例9: ListenDebugger

def ListenDebugger(port_ovr=None):
    """
	Start a debug server for Python Tools for Visual Studio (ptvs)
	"""
    import ptvsd

    if port_ovr:
        ptvsd.enable_attach(secret=PTVS_SECRET, address=("0.0.0.0", port_ovr), redirect_output=False)
    else:
        ptvsd.enable_attach(secret=PTVS_SECRET, redirect_output=False)

    GEUtil.Msg("Python debugger successfully connected!\n")
开发者ID:J-Shep,项目名称:ges-python,代码行数:12,代码来源:ge_debugger.py


示例10: debug

def debug(_connection=None):
    output = sims4.commands.CheatOutput(_connection)
    output("Connecting to Debugger")
    print("Connecting to Debugger")
    failed = True
    if failed:
        try:
            # Try connecting to Python Tools for Visual Studio 
            #   Note that you need ptvsd.zip in the Mods folder
            #   You also need ctypes from python33\lib in the ptvsd.zip 
            #   as well as _ctypes.pyd copied to Origin\Game\bin\Python\DLLs
            #   You would connect to this machine after this command
            import ptvsd
            ptvsd.enable_attach(secret='ts4')
            # ptvsd.wait_for_attach(timeout=20.0) # wait for 20 seconds?
            failed = False
        except Exception as e:
            import sys, traceback
            print(str(e), file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            pass
            
    if failed:
        try:
            # Try connecting to PyCharm or IntelliJ IDEA Professional
            #   Note that you need pycharm-debug-py3k.egg in the Mods folder
            #   and .egg renamed to .zip for this to work.
            #  Startup the Python Remote Debug Configuration before running this command.
            import pydevd
            pydevd.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True)
            failed = False
        except Exception as e:
            import sys, traceback
            print(str(e), file=sys.stderr)
            traceback.print_exc(file=sys.stderr)
            pass
        

    if failed:
        output("Exception while connecting to Debugger")
        print("Exception while connecting to Debugger")    
    else:
        output("Continuing Debugger")
        print("Continuing Debugger")
    return False
开发者ID:figment,项目名称:sims4exmod,代码行数:45,代码来源:debug.py


示例11: debug

def debug():

    """
    Wait for debugger attach.
    """

    try:
        import os
        import inspect
        import ptvsd
        module_root = os.path.dirname(inspect.getfile(main))
        print("Debug mode enabled. Waiting for debugger attach.")
        print("    remote root:", module_root)
        print("    debug port:", 5151)
        print("    debug secret:", "debug_secret")
        ptvsd.enable_attach("debug_secret", address = ('0.0.0.0', 5151))
        ptvsd.wait_for_attach()
    except ImportError:
        print("Debug prerequisites not avalible.")
    
    main()
开发者ID:intel-iot-devkit,项目名称:how-to-code-samples,代码行数:21,代码来源:__main__.py


示例12: ListenDebugger

def ListenDebugger( port_ovr=None ):
    '''
    Start a debug server for Python Tools for Visual Studio (ptvs)
    '''
    try:
        if port_ovr:
            ptvsd.enable_attach( secret=PTVS_SECRET, address=('0.0.0.0', port_ovr), redirect_output=False )
        else:
            ptvsd.enable_attach( secret=PTVS_SECRET, redirect_output=False )

        print( "Listening for Python Tools for Visual Studio debugger, version %s\n" % ptvsd.attach_server.PTVS_VER )
    
    except AttachAlreadyEnabledError:
        Warning( "Python debugger is already listening!\n" )
        
    print( "To connect using Visual Studio 2013 & PTVS:" )
    print( "  1) DEBUG -> Attach to process..." )
    print( "  2) Select Python Remote (ptvsd) from the Transport menu" )
    print( "  3) Enter tcp://%[email protected]:5678 in the Qualifier field and press Refresh" % PTVS_SECRET )
    print( "  4) Click Attach to start debugging" )
    print( "\nGood Luck and happy coding!\n" )
开发者ID:goldeneye-source,项目名称:ges-python,代码行数:21,代码来源:ge_debugger.py


示例13: attach_to_pid

def attach_to_pid():
    def quoted_str(s):
        assert not isinstance(s, bytes)
        unescaped = set(chr(ch) for ch in range(32, 127)) - {'"', "'", '\\'}
        def escape(ch):
            return ch if ch in unescaped else '\\u%04X' % ord(ch)
        return 'u"' + ''.join(map(escape, s)) + '"'

    pid = ptvsd.options.target
    host = quoted_str(ptvsd.options.host)
    port = ptvsd.options.port

    ptvsd_path = os.path.abspath(os.path.join(ptvsd.__file__, '../..'))
    if isinstance(ptvsd_path, bytes):
        ptvsd_path = ptvsd_path.decode(sys.getfilesystemencoding())
    ptvsd_path = quoted_str(ptvsd_path)

    # pydevd requires injected code to not contain any single quotes.
    code = '''
import os
assert os.getpid() == {pid}

import sys
sys.path.insert(0, {ptvsd_path})
import ptvsd
del sys.path[0]

import ptvsd.options
ptvsd.options.client = True
ptvsd.options.host = {host}
ptvsd.options.port = {port}

ptvsd.enable_attach()
'''.format(**locals())
    print(code)

    pydevd_attach_to_process_path = os.path.join(
        os.path.dirname(pydevd.__file__),
        'pydevd_attach_to_process')
    sys.path.insert(0, pydevd_attach_to_process_path)
    from add_code_to_python_process import run_python_code
    run_python_code(pid, code, connect_debugger_tracing=True)
开发者ID:andrewgu12,项目名称:config,代码行数:42,代码来源:__main__.py


示例14:

import ptvsd
ptvsd.enable_attach(secret=None)
from time import sleep

print("hi")

X = raw_input("Response: ")

sleep(1)

print(":D")

sleep(1)

Y = raw_input("Response: ")
开发者ID:hobnob11,项目名称:Pi-thon,代码行数:15,代码来源:test.py


示例15: getAccount

from azure.storage import TableService, Entity, QueueService
import time
import redis
import spidev
from tokens import *
import ptvsd
ptvsd.enable_attach('xplatDebug')

spi = spidev.SpiDev()
spi.open(0,0)

myaccount = getAccount()
mykey = getKey()

table_service = TableService(account_name=myaccount, account_key=mykey)
queue_service = QueueService(account_name=myaccount, account_key=mykey)

queue_service.create_queue('acceldata')

i = 0

TableSlotList = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,43,44,45,46,47,48,49,50)

periods = ('a', 'b', 'c', 'd')

#table_service.insert_or_replace_entity(accel2, accel, tableSlot, periodSlot)

record = {}

#records = {'aX': generateX(),'aY': generateY(),'aZ': generateZ(),'bX': generateX(),'bY': generateY(),'bZ': generateZ(), 'cX': generateX(),'cY': generateY(),'cZ': generateZ(),'cX': generateX(),'cY': generateY(),'cZ': generateZ() }
开发者ID:timmyreilly,项目名称:raspberryHug,代码行数:30,代码来源:SendCloudData.py


示例16: main

def main():
    initialized = False
    log('wfastcgi.py %s started' % __version__)
    log('Python version: %s' % sys.version)

    try:
        fcgi_stream = sys.stdin.detach() if sys.version_info[0] >= 3 else sys.stdin
        try:
            import msvcrt
            msvcrt.setmode(fcgi_stream.fileno(), os.O_BINARY)
        except ImportError:
            pass

        while True:
            record = read_fastcgi_record(fcgi_stream)
            if not record:
                continue

            errors = sys.stderr = sys.__stderr__ = record.params['wsgi.errors'] = StringIO()
            output = sys.stdout = sys.__stdout__ = StringIO()

            with handle_response(fcgi_stream, record, output.getvalue, errors.getvalue) as response:
                if not initialized:
                    log('wfastcgi.py %s initializing' % __version__)

                    os.chdir(response.physical_path)
                    sys.path[0] = '.'

                    # Initialization errors should be treated as fatal.
                    response.fatal_errors = True
                    response.error_message = 'Error occurred while reading WSGI handler'
                    env, handler = read_wsgi_handler(response.physical_path)

                    response.error_message = 'Error occurred starting file watcher'
                    start_file_watcher(response.physical_path, env.get('WSGI_RESTART_FILE_REGEX'))

                    # Enable debugging if possible. Default to local-only, but
                    # allow a web.config to override where we listen
                    ptvsd_secret = env.get('WSGI_PTVSD_SECRET')
                    if ptvsd_secret:
                        ptvsd_address = (env.get('WSGI_PTVSD_ADDRESS') or 'localhost:5678').split(':', 2)
                        try:
                            ptvsd_port = int(ptvsd_address[1])
                        except LookupError:
                            ptvsd_port = 5678
                        except ValueError:
                            log('"%s" is not a valid port number for debugging' % ptvsd_address[1])
                            ptvsd_port = 0

                        if ptvsd_address[0] and ptvsd_port:
                            try:
                                import ptvsd
                            except ImportError:
                                log('unable to import ptvsd to enable debugging')
                            else:
                                addr = ptvsd_address[0], ptvsd_port
                                ptvsd.enable_attach(secret=ptvsd_secret, address=addr)
                                log('debugging enabled on %s:%s' % addr)

                    response.error_message = ''
                    response.fatal_errors = False

                    log('wfastcgi.py %s initialized' % __version__)
                    initialized = True

                os.environ.update(env)

                # SCRIPT_NAME + PATH_INFO is supposed to be the full path
                # (http://www.python.org/dev/peps/pep-0333/) but by default
                # (http://msdn.microsoft.com/en-us/library/ms525840(v=vs.90).aspx)
                # IIS is sending us the full URL in PATH_INFO, so we need to
                # clear the script name here
                if 'AllowPathInfoForScriptMappings' not in os.environ:
                    record.params['SCRIPT_NAME'] = ''
                    record.params['wsgi.script_name'] = wsgi_encode('')

                # correct SCRIPT_NAME and PATH_INFO if we are told what our SCRIPT_NAME should be
                if 'SCRIPT_NAME' in os.environ and record.params['PATH_INFO'].lower().startswith(os.environ['SCRIPT_NAME'].lower()):
                    record.params['SCRIPT_NAME'] = os.environ['SCRIPT_NAME']
                    record.params['PATH_INFO'] = record.params['PATH_INFO'][len(record.params['SCRIPT_NAME']):]
                    record.params['wsgi.script_name'] = wsgi_encode(record.params['SCRIPT_NAME'])
                    record.params['wsgi.path_info'] = wsgi_encode(record.params['PATH_INFO'])

                # Send each part of the response to FCGI_STDOUT.
                # Exceptions raised in the handler will be logged by the context
                # manager and we will then wait for the next record.

                result = handler(record.params, response.start)
                try:
                    for part in result:
                        if part:
                            response.send(FCGI_STDOUT, part)
                finally:
                    if hasattr(result, 'close'):
                        result.close()
    except _ExitException:
        pass
    except Exception:
        maybe_log('Unhandled exception in wfastcgi.py: ' + traceback.format_exc())
    except BaseException:
#.........这里部分代码省略.........
开发者ID:BMBurstein,项目名称:PTVS,代码行数:101,代码来源:wfastcgi.py


示例17: len

            offset = offset + len(urls)
            logging.warn('got {} likes'.format(offset))
            if (offset >= total_count or len(urls) == 0):
                break
        return liked_urls

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--downloadDir", default="download")
    parser.add_argument("--blogName")
    parser.add_argument("--secretFile", default="secret.txt")
    parser.add_argument("--debug", action="store_true")
    args = parser.parse_args()

    if (args.debug):
        import ptvsd
        ptvsd.enable_attach(secret='secret')
        ptvsd.wait_for_attach()

    setup_logger(logging.INFO)
    socks.set_default_proxy(socks.SOCKS5, "localhost")
    socket.socket = socks.socksocket
    def getaddrinfo(*args):
        return [(socket.AF_INET, socket.SOCK_STREAM, 6, '', (args[0], args[1]))]
    socket.getaddrinfo = getaddrinfo

    d = DownloadLikes(downloaddir=args.downloadDir, blogName=args.blogName, secretFile=args.secretFile)
    d.Download()
    d.close()

开发者ID:hjk41,项目名称:tumblrvideodownloader,代码行数:29,代码来源:DownloadLikes.py


示例18:

from flansible import app, config
import platform
#Visual studio remote debugger
if platform.node() == 'mgmt':
    try:
        import ptvsd
        ptvsd.enable_attach(secret='my_secret', address = ('0.0.0.0', 3000))
    except:
        pass

if __name__ == '__main__':
    app.run(debug=True, host=config.get("Default", "Flask_tcp_ip"), use_reloader=False, port=int(config.get("Default", "Flask_tcp_port")))
开发者ID:trondhindenes,项目名称:flansible,代码行数:12,代码来源:runserver.py


示例19:

# -*- coding: utf-8 -*-

import ptvsd
import platform

ptvsd.enable_attach(secret = 'thinkAmi')

os = platform.system()

print u'ここでアタッチを待ちます'

if os != 'Windows':
    ptvsd.wait_for_attach()

print u'platform.systemの結果は %s です' % os
开发者ID:thinkAmi-sandbox,项目名称:PTVS-remote_debug-sample,代码行数:15,代码来源:ptvs_raspberrypi.py


示例20: PiStorms

# coding: utf-8

# for ptvsd debug.
import ptvsd        
import platform

import os
import sys
import inspect
import time

# for ptvsd debug.
ptvsd.enable_attach(secret = 'ptvsd')
os = platform.system()
print 'Waiting for attach...'
if os != 'Windows':
    ptvsd.wait_for_attach()

# common three lines need for each PiStorms programs.
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)

# import PiStorms library.
from PiStorms import PiStorms
psm = PiStorms()

# print a message on the screen.
psm.screen.termPrintln("EV3 touch sensor readout (BBS1):")
psm.screen.termPrintln(" ")
开发者ID:gundamsan,项目名称:HelloPython,代码行数:30,代码来源:HelloPiStorms.py



注:本文中的ptvsd.enable_attach函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python pty.fork函数代码示例发布时间:2022-05-25
下一篇:
Python readers.BaseEventReader类代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap