sys.path.insert

Here are the examples of the python api sys.path.insert taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: rietveld
Source File: setup.py
View license
def setup_test_env(sdk_path):
  """Sets up App Engine/Django test environment."""
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../'))
  sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../third_party'))
  sys.path.insert(0, sdk_path)
  import dev_appserver
  dev_appserver.fix_sys_path()
  # google.appengine.ext.testbed.Testbed should set SERVER_SOFTWARE
  # and APPLICATION_ID environment variables, but we need them
  # earlier when Django import settings.py.
  os.environ['SERVER_SOFTWARE'] = 'DevTestrunner'  # used in settings.py
  os.environ['APPLICATION_ID'] = 'test-codereview'  # used in settings.py
  os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
  # Provide a dummy value for REQUEST_ID_HASH in environment. This is
  # needed for now to make appstats happy (see comments on
  # http://codereview.appspot.com/5305060/).
  os.environ['REQUEST_ID_HASH'] = 'testing'
  from google.appengine.dist import use_library
  use_library('django', '1.3')

Example 2

Project: qutepart
Source File: editor.py
View license
def _fixSysPath(binaryQutepart):
    executablePath = os.path.abspath(__file__)
    if executablePath.startswith('/home'):  # if executed from the sources
        qutepartDir = os.path.dirname(executablePath)
        sys.path.insert(0, qutepartDir)  # do not import installed modules
        if binaryQutepart:
            sys.path.insert(0, qutepartDir + '/build/lib.linux-i686-3.3/')  # use built modules
            sys.path.insert(0, qutepartDir + '/build/lib.linux-i686-3.4/')  # use built modules
            sys.path.insert(0, qutepartDir + '/build/lib.linux-x86_64-3.3/')  # use built modules
            sys.path.insert(0, qutepartDir + '/build/lib.linux-x86_64-3.4/')  # use built modules

Example 3

View license
def main(sdk_path, test_path):
  sys.path.insert(0, sdk_path)
  sys.path.insert(0, os.path.join(test_path, '../'))
  sys.path.insert(0, os.path.join(test_path))
  import dev_appserver
  dev_appserver.fix_sys_path()
  suite = unittest.loader.TestLoader().discover(test_path)
  unittest.TextTestRunner(verbosity=10).run(suite)

Example 4

Project: pyyaml
Source File: setup.py
View license
    def run(self):
        build_cmd = self.get_finalized_command('build')
        build_cmd.run()
        sys.path.insert(0, build_cmd.build_lib)
        if sys.version_info[0] < 3:
            sys.path.insert(0, 'tests/lib')
        else:
            sys.path.insert(0, 'tests/lib3')
        import test_all
        if not test_all.main([]):
            raise DistutilsError("Tests failed")

Example 5

Project: typefacet
Source File: setup.py
View license
    def run(self):
        build_cmd = self.get_finalized_command('build')
        build_cmd.run()
        sys.path.insert(0, build_cmd.build_lib)
        if sys.version_info[0] < 3:
            sys.path.insert(0, 'tests/lib')
        else:
            sys.path.insert(0, 'tests/lib3')
        import test_all
        test_all.main([])

Example 6

Project: Python-mode-klen
Source File: utils.py
View license
def patch_paths():
    """ Function description. """
    sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs'))

    if PY2:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs2'))
    else:
        sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'libs3'))

Example 7

View license
def unit_test():
    print 'Running unit test'
    sys.path.insert(0, env.COMMAND_HELPER_DIR)
    sys.path.insert(0, env.SETTING_DIR)
    sys.path.insert(0, env.SRC_DIR)
    sys.path.append(env.UNIT_TEST_DIR)
    # suite = unittest.TestLoader().loadTestsFromName(
    #     'test_current_view.TestIndexing.test_create_view')
    suite = unittest.TestLoader().discover(
        start_dir=env.UNIT_TEST_DIR,
        pattern='test*.py')
    return unittest.TextTestRunner(verbosity=2).run(suite)

Example 8

Project: spotimc
Source File: environment.py
View license
def set_library_paths():
    #Set local library paths
    libs_dir = os.path.join(__addon_path__, "resources/libs")
    sys.path.insert(0, libs_dir)
    sys.path.insert(0, os.path.join(libs_dir, "xbmc-skinutils/src"))
    sys.path.insert(0, os.path.join(libs_dir, "cherrypy"))
    sys.path.insert(0, os.path.join(libs_dir, "taskutils/src"))
    sys.path.insert(0, os.path.join(libs_dir, "pyspotify-ctypes/src"))
    sys.path.insert(0, os.path.join(libs_dir, "pyspotify-ctypes-proxy/src"))

Example 9

Project: Letterpress
Source File: test.py
View license
def setup():
    top_dir = dirname(dirname(abspath(__file__)))
    lib_dir = join(top_dir, "lib")
    sys.path.insert(0, lib_dir)

    # Attempt to get 'pygments' on the import path.
    try:
        # If already have it, use that one.
        import pygments
    except ImportError:
        pygments_dir = join(top_dir, "deps", "pygments")
        if sys.version_info[0] <= 2:
            sys.path.insert(0, pygments_dir)
        else:
            sys.path.insert(0, pygments_dir + "3")

Example 10

Project: stashboard
Source File: runner.py
View license
def main():
    #logging.basicConfig(level=logging.DEBUG)
    sys.path.insert(0, SDK_PATH)
    sys.path.insert(0, "stashboard")
    sys.path.insert(0, "stashboard/contrib")
    import dev_appserver
    dev_appserver.fix_sys_path()
    nose.main()

Example 11

Project: ro-manager
Source File: TestAll.py
View license
def runTestSuite():
    """
    Transfer function for setup.py script ro-manager-test
    """
    base = os.path.dirname(__file__)
    #print "Run test suite assuming base path "+base
    sys.path.insert(0, os.path.normpath(base+"/..") )
    sys.path.insert(0, os.path.normpath(base+"/../..") )
    sys.path.insert(0, os.path.normpath(base+"/../../iaeval/test") )
    sys.path.insert(0, os.path.normpath(base+"/../../sync/test") )
    #print "Path: "+repr(sys.path)
    TestUtils.runTests("TestAll", getTestSuite, sys.argv)
    return 0

Example 12

Project: ro-manager
Source File: RunRoManagerTests.py
View license
def runTestSuite():
    """
    Transfer function for setup.py script ro-manager-test
    """
    base = os.path.dirname(__file__)
    os.chdir(base)
    #print "Run test suite assuming base path "+base
    sys.path.insert(0, os.path.normpath(base+"/..") )
    sys.path.insert(0, os.path.normpath(base+"/../..") )
    sys.path.insert(0, os.path.normpath(base+"/../../iaeval/test") )
    sys.path.insert(0, os.path.normpath(base+"/../../sync/test") )
    sys.path.insert(0, os.path.normpath(base+"/../../checklist/test") )
    sys.path.insert(0, os.path.normpath(base+"/../../roweb") )
    sys.path.insert(0, os.path.normpath(base+"/../../roweb/test") )
    #print "Path: "+repr(sys.path)
    import TestAll
    TestUtils.runTests("TestAll", TestAll.getTestSuite, sys.argv)
    return 0

Example 13

View license
    def __call__(self, req):
        # mod_python fakes the environ, and thus doesn't process SetEnv.
        # This fixes that. Django will call this again since there is no way
        # of overriding __call__ to just process the request.
        os.environ.update(req.subprocess_env)
        from django.conf import settings
        
        sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
        
        sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
        sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
        
        return super(PinaxModPythonHandler, self).__call__(req)

Example 14

Project: confista
Source File: modpython.py
View license
    def __call__(self, req):
        # mod_python fakes the environ, and thus doesn't process SetEnv.
        # This fixes that. Django will call this again since there is no way
        # of overriding __call__ to just process the request.
        os.environ.update(req.subprocess_env)
        from django.conf import settings
        
        sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
        
        sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
        sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
        
        return super(PinaxModPythonHandler, self).__call__(req)

Example 15

Project: hubplus
Source File: modpython.py
View license
    def __call__(self, req):
        # mod_python fakes the environ, and thus doesn't process SetEnv. 
        # This fixes that. Django will call this again since there is no way
        # of overriding __call__ to just process the request.
        os.environ.update(req.subprocess_env)
        from django.conf import settings
        
        sys.path.insert(0, abspath(join(dirname(__file__), "../../")))
        
        sys.path.insert(0, join(settings.PINAX_ROOT, "apps"))
        sys.path.insert(0, join(settings.PROJECT_ROOT, "apps"))
        
        return super(PinaxModPythonHandler, self).__call__(req)

Example 16

Project: Observatory
Source File: fetch_core.py
View license
def setup_environment():
  path = os.path.dirname(os.path.abspath(__file__))
  sys.path.insert(0, path)
  sys.path.insert(0, os.path.abspath(os.path.join(path, '..', '..')))
  sys.path.insert(0, os.path.abspath(os.path.join(path, '..', '..', '..')))
  os.environ['DJANGO_SETTINGS_MODULE'] = 'observatory.settings'

Example 17

Project: netzob
Source File: test_command.py
View license
    def run(self):
        '''
        Finds all the tests modules in test/, and runs them.
        '''
        sys.path.insert(0, 'src/')

        #insert in the path the directory where _libNeedleman.pyd is
        if os.name == 'nt':
            sys.path.insert(0, 'lib/libNeedleman/')

        try:
            # Verify that libNeedleman is in the path
            from netzob import _libNeedleman
        except:
            # Else, assume the path is gotten from the 'python setup.py build' command
            arch = os.uname()[-1]
            python_version = sys.version[:3]
            build_lib_path = "build/lib.linux-" + arch + "-" + python_version
            sys.path.append(build_lib_path)

        sys.path.insert(0, 'test/src/')

        from common.xmlrunner import XMLTestRunner
        from test_netzob import suite_global
        #import netzob.NetzobGui as NetzobGui

        # We retrieve the current test suite
        currentTestSuite = suite_global.getSuite()

        if self.reportfile is None or len(self.reportfile) == 0:
            runner = unittest.TextTestRunner()
            testResult = runner.run(currentTestSuite)
        else:
            # We execute the test suite
            File = open(self.reportfile, 'w')
            File.write('<?xml version="1.0" encoding="utf-8"?>\n')
            reporter = XMLTestRunner(File)
            reporter.run(currentTestSuite)
            File.close()

            self.cleanFile(self.reportfile)

Example 18

Project: netzob
Source File: test_command.py
View license
    def run(self):
        '''
        Finds all the tests modules in test/, and runs them.
        '''
        sys.path.insert(0, 'src/')

        #insert in the path the directory where _libNeedleman.pyd is
        if os.name == 'nt':
            sys.path.insert(0, 'lib/libNeedleman/')

        try:
            # Verify that libNeedleman is in the path
            from netzob import _libNeedleman
        except:
            # Else, assume the path is gotten from the 'python setup.py build' command
            arch = os.uname()[-1]
            python_version = sys.version[:3]
            build_lib_path = "build/lib.linux-" + arch + "-" + python_version
            sys.path.append(build_lib_path)

        sys.path.insert(0, 'test/src/')

        from common.xmlrunner import XMLTestRunner
        from test_netzob import suite_global
        #import netzob.NetzobGui as NetzobGui

        # We retrieve the current test suite
        currentTestSuite = suite_global.getSuite()

        if self.reportfile is None or len(self.reportfile) == 0:
            runner = unittest.TextTestRunner()
            testResult = runner.run(currentTestSuite)
        else:
            # We execute the test suite
            File = open(self.reportfile, 'w')
            File.write('<?xml version="1.0" encoding="utf-8"?>\n')
            reporter = XMLTestRunner(File)
            reporter.run(currentTestSuite)
            File.close()

            self.cleanFile(self.reportfile)

Example 19

Project: cadquery-freecad-module
Source File: InitGui.py
View license
    def Activated(self):
        import os, sys
        import module_locator
        from Gui import Command, ImportCQ
        import Settings

        #Set up so that we can import from our embedded packages
        module_base_path = module_locator.module_path()
        libs_dir_path = os.path.join(module_base_path, 'Libs')
        sys.path.insert(0, libs_dir_path)

        # Tack on our CadQuery library git subtree
        cq_lib_path = os.path.join(libs_dir_path, 'cadquery-lib')
        sys.path.insert(1, cq_lib_path)

        #Make sure we get the right libs under the FreeCAD installation
        fc_base_path = os.path.dirname(os.path.dirname(module_base_path))
        fc_lib_path = os.path.join(fc_base_path, 'lib')
        fc_bin_path = os.path.join(fc_base_path, 'bin')

        #Make sure that the directories exist before we add them to sys.path
        #This could cause problems or solve them by overriding what CQ is setting for the paths
        if os.path.exists(fc_lib_path):
            sys.path.insert(1, fc_lib_path)
        if os.path.exists(fc_bin_path):
            sys.path.insert(1, fc_bin_path)

        import cadquery
        from pyqode.core.modes import FileWatcherMode
        from pyqode.python.widgets import PyCodeEdit
        from PySide import QtGui, QtCore

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "CadQuery " + cadquery.__version__ + "\r\n"
            "CadQuery is a parametric scripting language "
            "for creating and traversing CAD models\r\n"
            "Author: David Cowden\r\n"
            "License: Apache-2.0\r\n"
            "Website: https://github.com/dcowden/cadquery\r\n",
            None,
            QtGui.QApplication.UnicodeUTF8)
        FreeCAD.Console.PrintMessage(msg)

        #Make sure that we enforce a specific version (2.7) of the Python interpreter
        ver = hex(sys.hexversion)
        interpreter = "python%s.%s" % (ver[2], ver[4])  # => 'python2.7'

        #If the user doesn't have Python 2.7, warn them
        if interpreter != 'python2.7':
            msg = QtGui.QApplication.translate(
                "cqCodeWidget",
                "Please install Python 2.7",
                None,
                QtGui.QApplication.UnicodeUTF8)
            FreeCAD.Console.PrintError(msg + "\r\n")

        #The extra version numbers won't work on Windows
        if sys.platform.startswith('win'):
            interpreter = 'python'

        #Getting the main window will allow us to start setting things up the way we want
        mw = FreeCADGui.getMainWindow()

        dockWidgets = mw.findChildren(QtGui.QDockWidget)

        for widget in dockWidgets:
            if widget.objectName() == "Report view":
                widget.setVisible(True)

        #Add a new widget here that's a simple text area to begin with. It will become the CQ coding area
        cqCodeWidget = QtGui.QDockWidget("CadQuery Code View")
        cqCodeWidget.setObjectName("cqCodeView")
        mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cqCodeWidget)

        #Set up the text area for our CQ code
        server_path = os.path.join(module_base_path, 'cq_server.py')

        #Windows needs some extra help with paths
        if sys.platform.startswith('win'):
            codePane = PyCodeEdit(server_script=server_path, interpreter=interpreter
                                  , args=['-s', fc_lib_path, libs_dir_path])
        else:
            codePane = PyCodeEdit(server_script=server_path, interpreter=interpreter
                                  , args=['-s', libs_dir_path])

        # Allow easy use of an external editor
        if Settings.use_external_editor:
            codePane.modes.append(FileWatcherMode())
            codePane.modes.get(FileWatcherMode).file_reloaded.connect(self.AutoExecute)
            codePane.modes.get(FileWatcherMode).auto_reload = True

        codePane.setObjectName("cqCodePane")

        #Add the text area to our dock widget
        cqCodeWidget.setWidget(codePane)

        #Set up the paths to allow us to open and execute our introduction example
        #example_path = os.path.join(module_base_path, 'Examples')
        #example_path = os.path.join(example_path, 'Ex000_Introduction.py')

        # TODO: Enable this for FreeCAD 0.16 or greater
        # Make sure we get the correct MdiArea object
        # for child in mw.children():
        #     if child.__class__ == QtGui.QMdiArea:
        #         mdiArea = child
        #
        # # Set up the editor in a new subwindow
        # #sub_window = QtGui.QMdiSubWindow(mw.centralWidget())
        # sub_window = QtGui.QMdiSubWindow(mdiArea)
        # #sub_window.setWidget(codePane)
        # sub_window.setWidget(QtGui.QPlainTextEdit())
        # sub_window.setWindowTitle('Ex000_Introduction.py')
        # sub_window.setWindowIcon(QtGui.QIcon(':/icons/applications-python.svg'))
        #
        # #mw.centralWidget().addSubWindow(sub_window)
        # mdiArea.addSubWindow(sub_window)

        # Set up the paths to allow us to open the template
        template_path = os.path.join(module_base_path, 'Templates')
        template_path = os.path.join(template_path, 'script_template.py')

        ImportCQ.open(template_path)
        docname = os.path.splitext(os.path.basename(template_path))[0]

Example 20

Project: Nebula
Source File: nebula_osquery.py
View license
def hubble_versions():
    '''
    Report version of all hubble modules as query
    '''
    versions = {}

    # Nova
    if 'hubble.version' in __salt__:
        versions['nova'] = __salt__['hubble.version']()
    else:
        versions['nova'] = None

    # Nebula
    versions['nebula'] = version()

    # Pulsar
    if salt.utils.is_windows():
        try:
            sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_beacons/win_pulsar.py')))
            import win_pulsar
            versions['pulsar'] = win_pulsar.__version__
        except:
            versions['pulsar'] = None
    else:
        try:
            sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_beacons/pulsar.py')))
            import pulsar
            versions['pulsar'] = pulsar.__version__
        except:
            versions['pulsar'] = None

    # Quasar
    try:
        sys.path.insert(0, os.path.dirname(__salt__['cp.cache_file']('salt://_returners/splunk_nova_return.py')))
        import splunk_nova_return
        versions['quasar'] = splunk_nova_return.__version__
    except:
        versions['quasar'] = None

    return {'hubble_versions': {'data': [versions],
                                'result': True}}

Example 21

Project: cadquery-freecad-module
Source File: InitGui.py
View license
    def Activated(self):
        import os, sys
        import module_locator
        from Gui import Command, ImportCQ
        import Settings

        #Set up so that we can import from our embedded packages
        module_base_path = module_locator.module_path()
        libs_dir_path = os.path.join(module_base_path, 'Libs')
        sys.path.insert(0, libs_dir_path)

        # Tack on our CadQuery library git subtree
        cq_lib_path = os.path.join(libs_dir_path, 'cadquery-lib')
        sys.path.insert(1, cq_lib_path)

        #Make sure we get the right libs under the FreeCAD installation
        fc_base_path = os.path.dirname(os.path.dirname(module_base_path))
        fc_lib_path = os.path.join(fc_base_path, 'lib')
        fc_bin_path = os.path.join(fc_base_path, 'bin')

        #Make sure that the directories exist before we add them to sys.path
        #This could cause problems or solve them by overriding what CQ is setting for the paths
        if os.path.exists(fc_lib_path):
            sys.path.insert(1, fc_lib_path)
        if os.path.exists(fc_bin_path):
            sys.path.insert(1, fc_bin_path)

        import cadquery
        from pyqode.core.modes import FileWatcherMode
        from pyqode.python.widgets import PyCodeEdit
        from PySide import QtGui, QtCore

        msg = QtGui.QApplication.translate(
            "cqCodeWidget",
            "CadQuery " + cadquery.__version__ + "\r\n"
            "CadQuery is a parametric scripting language "
            "for creating and traversing CAD models\r\n"
            "Author: David Cowden\r\n"
            "License: Apache-2.0\r\n"
            "Website: https://github.com/dcowden/cadquery\r\n",
            None,
            QtGui.QApplication.UnicodeUTF8)
        FreeCAD.Console.PrintMessage(msg)

        #Make sure that we enforce a specific version (2.7) of the Python interpreter
        ver = hex(sys.hexversion)
        interpreter = "python%s.%s" % (ver[2], ver[4])  # => 'python2.7'

        #If the user doesn't have Python 2.7, warn them
        if interpreter != 'python2.7':
            msg = QtGui.QApplication.translate(
                "cqCodeWidget",
                "Please install Python 2.7",
                None,
                QtGui.QApplication.UnicodeUTF8)
            FreeCAD.Console.PrintError(msg + "\r\n")

        #The extra version numbers won't work on Windows
        if sys.platform.startswith('win'):
            interpreter = 'python'

        #Getting the main window will allow us to start setting things up the way we want
        mw = FreeCADGui.getMainWindow()

        dockWidgets = mw.findChildren(QtGui.QDockWidget)

        for widget in dockWidgets:
            if widget.objectName() == "Report view":
                widget.setVisible(True)

        #Add a new widget here that's a simple text area to begin with. It will become the CQ coding area
        cqCodeWidget = QtGui.QDockWidget("CadQuery Code View")
        cqCodeWidget.setObjectName("cqCodeView")
        mw.addDockWidget(QtCore.Qt.LeftDockWidgetArea, cqCodeWidget)

        #Set up the text area for our CQ code
        server_path = os.path.join(module_base_path, 'cq_server.py')

        #Windows needs some extra help with paths
        if sys.platform.startswith('win'):
            codePane = PyCodeEdit(server_script=server_path, interpreter=interpreter
                                  , args=['-s', fc_lib_path, libs_dir_path])
        else:
            codePane = PyCodeEdit(server_script=server_path, interpreter=interpreter
                                  , args=['-s', libs_dir_path])

        # Allow easy use of an external editor
        if Settings.use_external_editor:
            codePane.modes.append(FileWatcherMode())
            codePane.modes.get(FileWatcherMode).file_reloaded.connect(self.AutoExecute)
            codePane.modes.get(FileWatcherMode).auto_reload = True

        codePane.setObjectName("cqCodePane")

        #Add the text area to our dock widget
        cqCodeWidget.setWidget(codePane)

        #Set up the paths to allow us to open and execute our introduction example
        #example_path = os.path.join(module_base_path, 'Examples')
        #example_path = os.path.join(example_path, 'Ex000_Introduction.py')

        # TODO: Enable this for FreeCAD 0.16 or greater
        # Make sure we get the correct MdiArea object
        # for child in mw.children():
        #     if child.__class__ == QtGui.QMdiArea:
        #         mdiArea = child
        #
        # # Set up the editor in a new subwindow
        # #sub_window = QtGui.QMdiSubWindow(mw.centralWidget())
        # sub_window = QtGui.QMdiSubWindow(mdiArea)
        # #sub_window.setWidget(codePane)
        # sub_window.setWidget(QtGui.QPlainTextEdit())
        # sub_window.setWindowTitle('Ex000_Introduction.py')
        # sub_window.setWindowIcon(QtGui.QIcon(':/icons/applications-python.svg'))
        #
        # #mw.centralWidget().addSubWindow(sub_window)
        # mdiArea.addSubWindow(sub_window)

        # Set up the paths to allow us to open the template
        template_path = os.path.join(module_base_path, 'Templates')
        template_path = os.path.join(template_path, 'script_template.py')

        ImportCQ.open(template_path)
        docname = os.path.splitext(os.path.basename(template_path))[0]

Example 22

View license
def load_network(code_path, babi_train_raw, babi_test_raw, word2vec, word_vector_size, model_json):
    if model_json in loaded_models:
        print "!> model %s is already loaded" % model_json
        return loaded_models[model_json]

    print "!> loading model %s..." % model_json

    model_file = open(model_json)
    args_dict = json.load(model_file)

    assert word_vector_size == args_dict['word_vector_size']

    args_dict['babi_train_raw'] = babi_train_raw
    args_dict['babi_test_raw'] = babi_test_raw
    args_dict['word2vec'] = word2vec

    # init class
    if args_dict['network'] == 'dmn_batch':
        raise Exception("dmn_batch did not implement predict()")
        sys.path.insert(0, code_path)
        import dmn_batch
        dmn = dmn_batch.DMN_batch(**args_dict)
        sys.path.insert(0, current_dir)


    elif args_dict['network'] == 'dmn_basic':
        raise Exception("dmn_batch did not implement predict()")
        sys.path.insert(0, code_path)
        import dmn_basic
        dmn = dmn_basic.DMN_basic(**args_dict)
        sys.path.insert(0, current_dir)


    elif args_dict['network'] == 'dmn_smooth':
        sys.path.insert(0, code_path)
        import dmn_smooth
        dmn = dmn_smooth.DMN_smooth(**args_dict)
        sys.path.insert(0, current_dir)

    elif args_dict['network'] == 'dmn_qa':
        raise Exception("dmn_batch did not implement predict()")

        sys.path.insert(0, code_path)
        import dmn_qa_draft
        dmn = dmn_qa_draft.DMN_qa(**args_dict)
        sys.path.insert(0, current_dir)

    else:
        raise Exception("No such network known: " + args_dict['network'])

    print "!> loading state %s..." % args_dict['load_state']

    dmn.load_state(args_dict['load_state'])

    loaded_models[model_json] = dmn

    return dmn

Example 23

Project: entropy
Source File: magneto_app.py
View license
def _startup(unlock_callback):
    sys.path.insert(0, "/usr/lib/rigo")
    sys.path.insert(0, "/usr/lib/entropy/client")
    sys.path.insert(0, "/usr/lib/entropy/lib")
    sys.path.insert(0, "/usr/lib/entropy/magneto")
    sys.path.insert(0, "../rigo")
    sys.path.insert(0, "../../client")
    sys.path.insert(0, "../../lib")
    sys.path.insert(0, "./")

    startup_delay = None
    for arg in sys.argv[1:]:
        if arg.startswith("--startup-delay="):
            try:
                delay = int(arg[len("--startup-delay="):])
                if delay < 1 and delay > 300:
                    raise ValueError()
                startup_delay = delay
            except ValueError:
                pass

    if startup_delay:
        time.sleep(startup_delay)

    kde_env = os.getenv("KDE_FULL_SESSION")
    desktop_session = os.getenv("DESKTOP_SESSION")
    is_mate = desktop_session == "MATE"

    if "--kde" in sys.argv:
        from magneto.kde.interfaces import Magneto
    elif "--gtk" in sys.argv:
        from magneto.gtk.interfaces import Magneto
    elif "--gtk3" in sys.argv:
        from magneto.gtk3.interfaces import Magneto
    else:
        if kde_env is not None:
            # this is KDE!
            try:
                from magneto.kde.interfaces import Magneto
            except (ImportError, RuntimeError,):
                # try GTK3, then GTK
                try:
                    from magneto.gtk3.interfaces import Magneto
                except ImportError:
                    from magneto.gtk.interfaces import Magneto
        elif is_mate:
            # Load GTK2, fallback to GTK3
            try:
                from magneto.gtk.interfaces import Magneto
            except ImportError:
                from magneto.gtk3.interfaces import Magneto
        else:
            # load GTK3, fallback to GTK2
            try:
                from magneto.gtk3.interfaces import Magneto
            except ImportError:
                from magneto.gtk.interfaces import Magneto

    import entropy.tools
    magneto = Magneto()
    magneto.set_unlock_callback(unlock_callback)
    try:
        magneto.startup()
        magneto.close_service()
    except KeyboardInterrupt:
        try:
            magneto.close_service()
        except:
            pass
        raise
    raise SystemExit(0)

Example 24

View license
    def __init__(self, base_path, parallelization=5, scenarios=None,
                 verbosity=0, random=False, enable_xunit=False,
                 xunit_filename=None, tags=None, failfast=False,
                 auto_pdb=False):
        """ lettuce.Runner will try to find a terrain.py file and
        import it from within `base_path`
        """

        self.tags = tags
        self.explicit_features = []

        if isinstance(base_path, list):
            self.explicit_features = base_path
            base_path = os.path.dirname(base_path[0])

        sys.path.insert(0, base_path)
        self.loader = fs.FeatureLoader(base_path)
        self.verbosity = verbosity
        self.scenarios = scenarios and map(int, scenarios.split(",")) or None
        self.failfast = failfast
        if auto_pdb:
            autopdb.enable(self)

        sys.path.remove(base_path)

        if verbosity is 0:
            output = 'non_verbose'
        elif verbosity is 1:
            output = 'dots'
        elif verbosity is 2:
            output = 'scenario_names'
        elif verbosity is 3:
            output = 'shell_output'
        else:
            output = 'colored_shell_output'

        self.random = random

        if enable_xunit:
            xunit_output.enable(filename=xunit_filename)

        self._output = output

        self.parallelization = parallelization

Example 25

Project: renderizer
Source File: plugin.py
View license
def compile (pluginConfig):
    """invoked by Titanium's build scripts, runs the compilation process"""

    # hacky crap to get directory of currently running script file
    pluginConfig['script_dir'] = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    sys.path.insert(0, pluginConfig['script_dir'])

    # try to load images.yaml in a few different places
    locations = [
        'images.yaml',
        '../images.yaml',
        os.path.join(pluginConfig['script_dir'], 'images.yaml'),
        os.path.join(pluginConfig['project_dir'], 'images.yaml')
    ]

    for location in locations:
        try:
            test = yaml.load(open(location, 'r'))
            # Save the correct path to images.yaml
            yaml_path = location
            break
        except Exception:
            pass
    else:
        raise Exception('images.yaml file not found!')

    modCheck = ModCheck()

    backends = {}
    backends['illustrator'] = illustrator
    backends['inkscape'] = inkscape

    for name, desc in test.items():
        print 'Rendering group', name

        # Load up renderizer plugins for this backend
        plugins = []
        if 'plugins' in desc:
            for plugin in desc['plugins']:
                module = __import__(plugin)
                plugins.append(module.plugin(desc))

        # Explode image paths
        replacers = []
        for line in desc['images']:
            if '*' in line or '?' in line or '[' in line:
                replacers.append(line)
        for line in replacers:
            desc['images'].remove(line)
            desc['images'].extend(glob.glob(os.path.join(pluginConfig['project_dir'], 'images', line)))

        for outputConfig in desc['output']:

            # validation
            if 'backend' not in desc:
                raise Exception(
                    "You must specify a render backend for output number " +
                    str(desc['output'].index(outputConfig)) + " in image group "
                    + name
                )

            if desc['backend'] not in backends :
                raise Exception(
                    "Invalid backend " + outputConfig['backend'] +
                    "specified in image group " + name
                )

            groupMatchesTiProps = False

            # check properties on the group itself; if these don't match we set
            # groupMatchesTiProps to false.  This will cause the output files
            # for this group to be removed, thereby cleaning the output
            # directory of links which dont match the current build
            # configuration
            if checkProps(TiBuildProps, pluginConfig, desc):
                groupMatchesTiProps = True

            # ensure the outputConfig directory exists
            try:
                os.makedirs(os.path.join(
                    pluginConfig['project_dir'],
                    outputConfig['path']
                ))
            except os.error:
                pass

            # ensure build directory exists
            try:
                os.makedirs(os.path.join(
                    pluginConfig['project_dir'],
                    'build', 'images',
                    outputConfig['path']
                ))
            except os.error:
                pass

            # render each sourceImage
            for sourceImage in desc['images']:

                # handle `rename` and `append` properties
                if 'rename' in outputConfig:
                    basename = outputConfig['rename']
                else:
                    basename = os.path.splitext(os.path.basename(sourceImage))[0]
                    if 'append' in outputConfig:
                        basename += outputConfig['append']
                    if 'prepend' in outputConfig:
                        basename = outputConfig['prepend'] + basename
                    basename += '.png'

                # compute filename and temp filename
                computedFilename = os.path.join(
                    pluginConfig['project_dir'],
                    outputConfig['path'],
                    basename
                )

                tempFilename = os.path.join(
                    pluginConfig['project_dir'],
                    'build', 'images',
                    outputConfig['path'],
                    basename
                )

                # generate path of source image
                sourceImage = os.path.join(
                    pluginConfig['project_dir'],
                    "images",
                    sourceImage
                )

                # check to see if we need to re-render the image; if so, render
                if not modCheck.check(sourceImage, tempFilename, outputConfig):
                    print sourceImage, 'not modified, not rendering'
                else:
                    # if we've gotten to this point, we're ready to render
                    renderBackend = backends[desc['backend']]

                    # loop over renderizer plugins, call the beforeRender function
                    for plugin in plugins:
                        plugin.beforeRender(sourceImage, tempFilename, outputConfig, pluginConfig)

                    renderBackend(
                        sourceImage,
                        tempFilename,
                        outputConfig,
                        pluginConfig
                    )

                    for plugin in plugins:
                        ret = plugin.afterRender(sourceImage, tempFilename, outputConfig, pluginConfig, computedFilename)
                        if ret != None:
                            computedFilename = ret

                # remove the output file; it will be replaced with a symlink to
                # the rendered image, if applicable
                try:
                    os.remove(computedFilename)
                except:
                    pass

                # replace the output file with a symlink to the rendered image
                # in build/images/, if the property check suceeds
                if checkProps(TiBuildProps, pluginConfig, outputConfig) and groupMatchesTiProps:
                    os.symlink(tempFilename, computedFilename)

Example 26

Project: qgisSpaceSyntaxToolkit
Source File: release.py
View license
def write_versionfile():
    """Creates a static file containing version information."""
    versionfile = os.path.join(basedir, 'version.py')

    text = '''"""
Version information for NetworkX, created during installation.

Do not add this file to the repository.

"""

import datetime

version = %(version)r
date = %(date)r

# Was NetworkX built from a development version? If so, remember that the major
# and minor versions reference the "target" (rather than "current") release.
dev = %(dev)r

# Format: (name, major, min, revision)
version_info = %(version_info)r

# Format: a 'datetime.datetime' instance
date_info = %(date_info)r

# Format: (vcs, vcs_tuple)
vcs_info = %(vcs_info)r

'''

    # Try to update all information
    date, date_info, version, version_info, vcs_info = get_info(dynamic=True)

    def writefile():
        fh = open(versionfile, 'w')
        subs = {
            'dev' : dev,
            'version': version,
            'version_info': version_info,
            'date': date,
            'date_info': date_info,
            'vcs_info': vcs_info
        }
        fh.write(text % subs)
        fh.close()

    if vcs_info[0] == 'mercurial':
        # Then, we want to update version.py.
        writefile()
    else:
        if os.path.isfile(versionfile):
            # This is *good*, and the most likely place users will be when
            # running setup.py. We do not want to overwrite version.py.
            # Grab the version so that setup can use it.
            sys.path.insert(0, basedir)
            from version import version
            del sys.path[0]
        else:
            # This is *bad*.  It means the user might have a tarball that
            # does not include version.py.  Let this error raise so we can
            # fix the tarball.
            ##raise Exception('version.py not found!')

            # We no longer require that prepared tarballs include a version.py
            # So we use the possibly trunctated value from get_info()
            # Then we write a new file.
            writefile()

    return version

Example 27

Project: YouCompleteMe-x86
Source File: utils.py
View license
def setup_readline(namespace_module=__main__):
    """
    Install Jedi completer to :mod:`readline`.

    This function setups :mod:`readline` to use Jedi in Python interactive
    shell.  If you want to use a custom ``PYTHONSTARTUP`` file (typically
    ``$HOME/.pythonrc.py``), you can add this piece of code::

        try:
            from jedi.utils import setup_readline
            setup_readline()
        except ImportError:
            # Fallback to the stdlib readline completer if it is installed.
            # Taken from http://docs.python.org/2/library/rlcompleter.html
            print("Jedi is not installed, falling back to readline")
            try:
                import readline
                import rlcompleter
                readline.parse_and_bind("tab: complete")
            except ImportError:
                print("Readline is not installed either. No tab completion is enabled.")

    This will fallback to the readline completer if Jedi is not installed.
    The readline completer will only complete names in the global namespace,
    so for example::

        ran<TAB>

    will complete to ``range``

    with both Jedi and readline, but::

        range(10).cou<TAB>

    will show complete to ``range(10).count`` only with Jedi.

    You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to
    your shell profile (usually ``.bash_profile`` or ``.profile`` if you use
    bash).

    """
    if READLINE_DEBUG:
        logging.basicConfig(
            filename='/tmp/jedi.log',
            filemode='a',
            level=logging.DEBUG
        )

    class JediRL(object):
        def complete(self, text, state):
            """
            This complete stuff is pretty weird, a generator would make
            a lot more sense, but probably due to backwards compatibility
            this is still the way how it works.

            The only important part is stuff in the ``state == 0`` flow,
            everything else has been copied from the ``rlcompleter`` std.
            library module.
            """
            if state == 0:
                sys.path.insert(0, os.getcwd())
                # Calling python doesn't have a path, so add to sys.path.
                try:
                    logging.debug("Start REPL completion: " + repr(text))
                    interpreter = Interpreter(text, [namespace_module.__dict__])

                    lines = common.splitlines(text)
                    position = (len(lines), len(lines[-1]))
                    name = get_on_completion_name(interpreter._get_module(), lines, position)
                    before = text[:len(text) - len(name)]
                    completions = interpreter.completions()
                except:
                    logging.error("REPL Completion error:\n" + traceback.format_exc())
                    raise
                finally:
                    sys.path.pop(0)

                self.matches = [before + c.name_with_symbols for c in completions]
            try:
                return self.matches[state]
            except IndexError:
                return None

    try:
        import readline
    except ImportError:
        print("Jedi: Module readline not available.")
    else:
        readline.set_completer(JediRL().complete)
        readline.parse_and_bind("tab: complete")
        # jedi itself does the case matching
        readline.parse_and_bind("set completion-ignore-case on")
        # because it's easier to hit the tab just once
        readline.parse_and_bind("set show-all-if-unmodified")
        readline.parse_and_bind("set show-all-if-ambiguous on")
        # don't repeat all the things written in the readline all the time
        readline.parse_and_bind("set completion-prefix-display-length 2")
        # No delimiters, Jedi handles that.
        readline.set_completer_delims('')

Example 28

Project: rad2py
Source File: web2py.py
View license
    def OnAttachWebserver(self, event):
        "start-up a web2py server instance"

        # read configuration with safe defaults        
        cfg = wx.GetApp().get_config("WEB2PY")
        path = cfg.get("path", "../web2py")
        password = cfg.get("password", "a")
        port = cfg.get("port", 8006)
        host = "127.0.0.1"
        
        if path:           
            # store current directory
            prevdir = os.path.abspath(os.curdir)
           
            try:
                # update current directory and python path to find web2py:
                os.chdir(path)
                sys.path.insert(0, os.path.abspath(os.curdir))
                from gluon.main import wsgibase, save_password
                from gluon.contrib import qdb

                # store admin password
                save_password(password, port)

                web2py_env = {} ##self.build_web2py_environment()

                # Start a alternate web2py in a separate thread (for blocking requests)
                from threading import Thread
                def server(host, port, password):
                    save_password(password, port)
                    qdb.init(redirect=False)
                    qdb.qdb.do_debug()

                    def wrapped_app(environ, start_response):
                        "WSGI wrapper to allow debugging"
                        # hanshake with front-end on each request (update ui)
                        # not realy needed (request processing is sequential)
                        ##qdb.qdb.startup()
                        # process the request as usual
                        return wsgibase(environ, start_response)

                    httpd2 = make_server(host, port, wrapped_app)
                    print "THREAD - Serving HTTP on port2 %s..." % port
                    httpd2.serve_forever(poll_interval=0.01)

                thread = Thread(target=server, args=(host, port, password))
                thread.daemon = True     # close on exit
                thread.start()

                # open internal browser at default page:
                url = "http://%s:%s/" % (host, port)
                if self.browser:
                    self.browser.LoadURL(url)
                    pass
                else:
                    # no internal browser, open external one
                    try:
                        import webbrowser
                        webbrowser.open(url)
                    except:
                        print 'warning: unable to detect your browser'
                                
            except Exception, e:
                self.ShowInfoBar(u"cannot start web2py!: %s" % unicode(e), 
                                 flags=wx.ICON_ERROR, key="web2py")
                web2py_env = {}
            finally:
                # recover original directory
                os.chdir(prevdir)
            self.web2py_environment = web2py_env

Example 29

Project: scoop
Source File: runpy.py
View license
def run_path(path_name, init_globals=None, run_name=None):
    """Execute code located at the specified filesystem location

       Returns the resulting top level namespace dictionary

       The file path may refer directly to a Python script (i.e.
       one that could be directly executed with execfile) or else
       it may refer to a zipfile or directory containing a top
       level __main__.py script.
    """
    if run_name is None:
        run_name = "<run_path>"
    importer = _get_importer(path_name)
    if isinstance(importer, imp.NullImporter):
        # Not a valid sys.path entry, so run the code directly
        # execfile() doesn't help as we want to allow compiled files
        code = _get_code_from_file(path_name)
        return _run_module_code(code, init_globals, run_name, path_name)
    else:
        # Importer is defined for path, so add it to
        # the start of sys.path
        sys.path.insert(0, path_name)
        try:
            # Here's where things are a little different from the run_module
            # case. There, we only had to replace the module in sys while the
            # code was running and doing so was somewhat optional. Here, we
            # have no choice and we have to remove it even while we read the
            # code. If we don't do this, a __loader__ attribute in the
            # existing __main__ module may prevent location of the new module.
            main_name = "__main__"
            saved_main = sys.modules[main_name]
            del sys.modules[main_name]
            try:
                mod_name, loader, code, fname = _get_main_module_details()
            finally:
                sys.modules[main_name] = saved_main
            pkg_name = ""
            with _ModifiedArgv0(path_name):
                with _TempModule(run_name) as temp_module:
                    mod_globals = temp_module.module.__dict__
                    return _run_code(code, mod_globals, init_globals,
                                        run_name, fname, loader, pkg_name).copy()
        finally:
            try:
                sys.path.remove(path_name)
            except ValueError:
                pass

Example 30

Project: pylons
Source File: commands.py
View license
    def command(self):
        """Main command to create a new shell"""
        self.verbose = 3
        if len(self.args) == 0:
            # Assume the .ini file is ./development.ini
            config_file = 'development.ini'
            if not os.path.isfile(config_file):
                raise BadCommand('%sError: CONFIG_FILE not found at: .%s%s\n'
                                 'Please specify a CONFIG_FILE' % \
                                 (self.parser.get_usage(), os.path.sep,
                                  config_file))
        else:
            config_file = self.args[0]

        config_name = 'config:%s' % config_file
        here_dir = os.getcwd()
        locs = dict(__name__="pylons-admin")

        if not self.options.quiet:
            # Configure logging from the config file
            self.logging_file_config(config_file)

        # Load locals and populate with objects for use in shell
        sys.path.insert(0, here_dir)

        # Load the wsgi app first so that everything is initialized right
        wsgiapp = loadapp(config_name, relative_to=here_dir)
        test_app = paste.fixture.TestApp(wsgiapp)

        # Query the test app to setup the environment
        tresponse = test_app.get('/_test_vars')
        request_id = int(tresponse.body)

        # Disable restoration during test_app requests
        test_app.pre_request_hook = lambda self: \
            paste.registry.restorer.restoration_end()
        test_app.post_request_hook = lambda self: \
            paste.registry.restorer.restoration_begin(request_id)

        # Restore the state of the Pylons special objects
        # (StackedObjectProxies)
        paste.registry.restorer.restoration_begin(request_id)

        # Determine the package name from the pylons.config object
        pkg_name = pylons.config['pylons.package']

        # Start the rest of our imports now that the app is loaded
        if is_minimal_template(pkg_name, True):
            model_module = None
            helpers_module = pkg_name + '.helpers'
            base_module = pkg_name + '.controllers'
        else:
            model_module = pkg_name + '.model'
            helpers_module = pkg_name + '.lib.helpers'
            base_module = pkg_name + '.lib.base'

        if model_module and can_import(model_module):
            locs['model'] = sys.modules[model_module]

        if can_import(helpers_module):
            locs['h'] = sys.modules[helpers_module]

        exec ('from pylons import app_globals, config, request, response, '
              'session, tmpl_context, url') in locs
        exec ('from pylons.controllers.util import abort, redirect') in locs
        exec 'from pylons.i18n import _, ungettext, N_' in locs
        locs.pop('__builtins__', None)

        # Import all objects from the base module
        __import__(base_module)

        base = sys.modules[base_module]
        base_public = [__name for __name in dir(base) if not \
                       __name.startswith('_') or __name == '_']
        locs.update((name, getattr(base, name)) for name in base_public)
        locs.update(dict(wsgiapp=wsgiapp, app=test_app))

        mapper = tresponse.config.get('routes.map')
        if mapper:
            locs['mapper'] = mapper

        banner = "  All objects from %s are available\n" % base_module
        banner += "  Additional Objects:\n"
        if mapper:
            banner += "  %-10s -  %s\n" % ('mapper', 'Routes mapper object')
        banner += "  %-10s -  %s\n" % ('wsgiapp',
            "This project's WSGI App instance")
        banner += "  %-10s -  %s\n" % ('app',
            'paste.fixture wrapped around wsgiapp')

        try:
            if self.options.disable_ipython:
                raise ImportError()

            # try to use IPython if possible
            try:
                try:
                    # 1.0 <= ipython
                    from IPython.terminal.embed import InteractiveShellEmbed
                except ImportError:
                    # 0.11 <= ipython < 1.0
                    from IPython.frontend.terminal.embed import InteractiveShellEmbed
                shell = InteractiveShellEmbed(banner2=banner)
            except ImportError:
                # ipython < 0.11
                from IPython.Shell import IPShellEmbed
                shell = IPShellEmbed(argv=self.args)
                shell.set_banner(shell.IP.BANNER + '\n\n' + banner)

            try:
                shell(local_ns=locs, global_ns={})
            finally:
                paste.registry.restorer.restoration_end()
        except ImportError:
            import code
            py_prefix = sys.platform.startswith('java') and 'J' or 'P'
            newbanner = "Pylons Interactive Shell\n%sython %s\n\n" % \
                (py_prefix, sys.version)
            banner = newbanner + banner
            shell = code.InteractiveConsole(locals=locs)
            try:
                import readline
            except ImportError:
                pass
            try:
                shell.interact(banner)
            finally:
                paste.registry.restorer.restoration_end()

Example 31

Project: scons
Source File: __init__.py
View license
    def Update(self, env, args=None):
        """
        Update an environment with the option variables.

        env - the environment to update.
        """

        values = {}

        # first set the defaults:
        for option in self.options:
            if not option.default is None:
                values[option.key] = option.default

        # next set the value specified in the options file
        for filename in self.files:
            if os.path.exists(filename):
                dir = os.path.split(os.path.abspath(filename))[0]
                if dir:
                    sys.path.insert(0, dir)
                try:
                    values['__name__'] = filename
                    exec open(filename, 'rU').read() in {}, values
                finally:
                    if dir:
                        del sys.path[0]
                    del values['__name__']

        # set the values specified on the command line
        if args is None:
            args = self.args

        for arg, value in args.items():
            added = False
            for option in self.options:
                if arg in list(option.aliases) + [ option.key ]:
                    values[option.key] = value
                    added = True
            if not added:
                self.unknown[arg] = value

        # put the variables in the environment:
        # (don't copy over variables that are not declared as options)
        for option in self.options:
            try:
                env[option.key] = values[option.key]
            except KeyError:
                pass

        # Call the convert functions:
        for option in self.options:
            if option.converter and option.key in values:
                value = env.subst('${%s}'%option.key)
                try:
                    try:
                        env[option.key] = option.converter(value)
                    except TypeError:
                        env[option.key] = option.converter(value, env)
                except ValueError, x:
                    raise SCons.Errors.UserError('Error converting option: %s\n%s'%(option.key, x))


        # Finally validate the values:
        for option in self.options:
            if option.validator and option.key in values:
                option.validator(option.key, env.subst('${%s}'%option.key), env)

Example 32

Project: SublimeJEDI
Source File: utils.py
View license
def setup_readline(namespace_module=__main__):
    """
    Install Jedi completer to :mod:`readline`.

    This function setups :mod:`readline` to use Jedi in Python interactive
    shell.  If you want to use a custom ``PYTHONSTARTUP`` file (typically
    ``$HOME/.pythonrc.py``), you can add this piece of code::

        try:
            from jedi.utils import setup_readline
            setup_readline()
        except ImportError:
            # Fallback to the stdlib readline completer if it is installed.
            # Taken from http://docs.python.org/2/library/rlcompleter.html
            print("Jedi is not installed, falling back to readline")
            try:
                import readline
                import rlcompleter
                readline.parse_and_bind("tab: complete")
            except ImportError:
                print("Readline is not installed either. No tab completion is enabled.")

    This will fallback to the readline completer if Jedi is not installed.
    The readline completer will only complete names in the global namespace,
    so for example::

        ran<TAB>

    will complete to ``range``

    with both Jedi and readline, but::

        range(10).cou<TAB>

    will show complete to ``range(10).count`` only with Jedi.

    You'll also need to add ``export PYTHONSTARTUP=$HOME/.pythonrc.py`` to
    your shell profile (usually ``.bash_profile`` or ``.profile`` if you use
    bash).

    """
    class JediRL(object):
        def complete(self, text, state):
            """
            This complete stuff is pretty weird, a generator would make
            a lot more sense, but probably due to backwards compatibility
            this is still the way how it works.

            The only important part is stuff in the ``state == 0`` flow,
            everything else has been copied from the ``rlcompleter`` std.
            library module.
            """
            if state == 0:
                sys.path.insert(0, os.getcwd())
                # Calling python doesn't have a path, so add to sys.path.
                try:
                    interpreter = Interpreter(text, [namespace_module.__dict__])

                    path = UserContext(text, (1, len(text))).get_path_until_cursor()
                    path, dot, like = completion_parts(path)
                    before = text[:len(text) - len(like)]
                    completions = interpreter.completions()
                finally:
                    sys.path.pop(0)

                self.matches = [before + c.name_with_symbols for c in completions]
            try:
                return self.matches[state]
            except IndexError:
                return None

    try:
        import readline
    except ImportError:
        print("Module readline not available.")
    else:
        readline.set_completer(JediRL().complete)
        readline.parse_and_bind("tab: complete")
        # jedi itself does the case matching
        readline.parse_and_bind("set completion-ignore-case on")
        # because it's easier to hit the tab just once
        readline.parse_and_bind("set show-all-if-unmodified")
        readline.parse_and_bind("set show-all-if-ambiguous on")
        # don't repeat all the things written in the readline all the time
        readline.parse_and_bind("set completion-prefix-display-length 2")
        # No delimiters, Jedi handles that.
        readline.set_completer_delims('')

Example 33

Project: mezzanine
Source File: runtests.py
View license
def main(package="mezzanine"):
    """
    This is the main test function called via ``python setup.py test``.
    It's responsible for hacking the ``project_template`` dir into
    an actual project to test against.
    """

    from mezzanine.utils.importing import path_for_import
    package_path = path_for_import(package)
    project_path = os.path.join(package_path, "project_template")

    os.environ["DJANGO_SETTINGS_MODULE"] = "project_name.test_settings"

    project_app_path = os.path.join(project_path, "project_name")

    local_settings_path = os.path.join(project_app_path, "local_settings.py")
    test_settings_path = os.path.join(project_app_path, "test_settings.py")

    sys.path.insert(0, package_path)
    sys.path.insert(0, project_path)

    if not os.path.exists(test_settings_path):
        shutil.copy(local_settings_path + ".template", test_settings_path)
        with open(test_settings_path, "r") as f:
            local_settings = f.read()
        with open(test_settings_path, "w") as f:
            test_settings = """

from . import settings

globals().update(i for i in settings.__dict__.items() if i[0].isupper())

# Require the mezzanine.accounts app. We use settings.INSTALLED_APPS here so
# the syntax test doesn't complain about an undefined name.
if "mezzanine.accounts" not in settings.INSTALLED_APPS:
    INSTALLED_APPS = list(settings.INSTALLED_APPS) + ["mezzanine.accounts"]

# Use the MD5 password hasher by default for quicker test runs.
PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)

"""
            f.write(test_settings + local_settings)

        def cleanup_test_settings():
            import os  # Outer scope sometimes unavailable in atexit functions.
            for fn in [test_settings_path, test_settings_path + 'c']:
                try:
                    os.remove(fn)
                except OSError:
                    pass
        atexit.register(cleanup_test_settings)

    django.setup()

    from django.core.management.commands import test
    if django.VERSION < (1, 10):
        sys.exit(test.Command().execute(verbosity=1))
    sys.exit(call_command(test.Command(), verbosity=1))

Example 34

Project: mrq
Source File: config.py
View license
def get_config(
        sources=(
            "file",
            "env"),
        env_prefix="MRQ_",
        file_path=None,
        parser=None,
        extra=None,
        config_type=None):
    """ Returns a config dict merged from several possible sources """

    if not parser:
        parser = argparse.ArgumentParser()

    add_parser_args(parser, config_type)
    parser_types = {action.dest: action.type for action in parser._actions if action.dest}

    if config_type in ["run"]:
        default_config = parser.parse_args(["notask"]).__dict__
    else:
        default_config = parser.parse_args([]).__dict__

    # Keys that can't be passed from the command line
    default_config["tasks"] = {}
    default_config["scheduled_tasks"] = {}

    # Only keep values different from config, actually passed on the command
    # line
    from_args = {}
    if "args" in sources:
        for k, v in parser.parse_args().__dict__.iteritems():
            if default_config[k] != v:
                from_args[k] = v

    # If we were given another config file, use it

    if file_path is not None:
        config_file = file_path
    elif from_args.get("config"):
        config_file = from_args.get("config")
    # If a mrq-config.py file is in the current directory, use it!
    elif os.path.isfile(os.path.join(os.getcwd(), "mrq-config.py")):
        config_file = os.path.join(os.getcwd(), "mrq-config.py")
    else:
        config_file = None

    from_file = {}
    if config_file and "file" in sources:
        sys.path.insert(0, os.path.dirname(config_file))
        config_module = __import__(os.path.basename(config_file.replace(".py", "")))
        sys.path.pop(0)
        for k, v in config_module.__dict__.iteritems():

            # We only keep variables starting with an uppercase character.
            if k[0].isupper():
                from_file[k.lower()] = v

    # Merge the config in the order given by the user
    merged_config = default_config

    config_keys = set(default_config.keys() + from_file.keys())

    for part in sources:
        for name in config_keys:

            if part == "env":
                value = os.environ.get(env_prefix + name.upper())
                if value:
                    if name == "queues":
                        value = re.split("\s+", value)
                    if parser_types.get(name):
                        value = parser_types[name](value)
                    merged_config[name] = value
            elif part == "args" and name in from_args:
                merged_config[name] = from_args[name]
            elif part == "file" and name in from_file:
                merged_config[name] = from_file[name]

    if extra:
        merged_config.update(extra)

    if merged_config["profile"]:
        import cProfile
        profiler = cProfile.Profile()
        profiler.enable()

        def print_profiling():
            profiler.print_stats(sort="cumulative")

        atexit.register(print_profiling)

    if merged_config["version"]:
        print "MRQ version: %s" % VERSION
        print "Python version: %s" % sys.version
        sys.exit(1)

    if "no_import_patch" in from_args:
        print "WARNING: --no_import_patch will be deprecated in MRQ 1.0!"

    return merged_config

Example 35

Project: pymo
Source File: test_zipimport_support.py
View license
    def test_doctest_issue4197(self):
        # To avoid having to keep two copies of the doctest module's
        # unit tests in sync, this test works by taking the source of
        # test_doctest itself, rewriting it a bit to cope with a new
        # location, and then throwing it in a zip file to make sure
        # everything still works correctly
        test_src = inspect.getsource(test_doctest)
        test_src = test_src.replace(
                         "from test import test_doctest",
                         "import test_zipped_doctest as test_doctest")
        test_src = test_src.replace("test.test_doctest",
                                    "test_zipped_doctest")
        test_src = test_src.replace("test.sample_doctest",
                                    "sample_zipped_doctest")
        sample_src = inspect.getsource(sample_doctest)
        sample_src = sample_src.replace("test.test_doctest",
                                        "test_zipped_doctest")
        with temp_dir() as d:
            script_name = make_script(d, 'test_zipped_doctest',
                                            test_src)
            zip_name, run_name = make_zip_script(d, 'test_zip',
                                                script_name)
            z = zipfile.ZipFile(zip_name, 'a')
            z.writestr("sample_zipped_doctest.py", sample_src)
            z.close()
            if verbose:
                zip_file = zipfile.ZipFile(zip_name, 'r')
                print 'Contents of %r:' % zip_name
                zip_file.printdir()
                zip_file.close()
            os.remove(script_name)
            sys.path.insert(0, zip_name)
            import test_zipped_doctest
            # Some of the doc tests depend on the colocated text files
            # which aren't available to the zipped version (the doctest
            # module currently requires real filenames for non-embedded
            # tests). So we're forced to be selective about which tests
            # to run.
            # doctest could really use some APIs which take a text
            # string or a file object instead of a filename...
            known_good_tests = [
                test_zipped_doctest.SampleClass,
                test_zipped_doctest.SampleClass.NestedClass,
                test_zipped_doctest.SampleClass.NestedClass.__init__,
                test_zipped_doctest.SampleClass.__init__,
                test_zipped_doctest.SampleClass.a_classmethod,
                test_zipped_doctest.SampleClass.a_property,
                test_zipped_doctest.SampleClass.a_staticmethod,
                test_zipped_doctest.SampleClass.double,
                test_zipped_doctest.SampleClass.get,
                test_zipped_doctest.SampleNewStyleClass,
                test_zipped_doctest.SampleNewStyleClass.__init__,
                test_zipped_doctest.SampleNewStyleClass.double,
                test_zipped_doctest.SampleNewStyleClass.get,
                test_zipped_doctest.old_test1,
                test_zipped_doctest.old_test2,
                test_zipped_doctest.old_test3,
                test_zipped_doctest.old_test4,
                test_zipped_doctest.sample_func,
                test_zipped_doctest.test_DocTest,
                test_zipped_doctest.test_DocTestParser,
                test_zipped_doctest.test_DocTestRunner.basics,
                test_zipped_doctest.test_DocTestRunner.exceptions,
                test_zipped_doctest.test_DocTestRunner.option_directives,
                test_zipped_doctest.test_DocTestRunner.optionflags,
                test_zipped_doctest.test_DocTestRunner.verbose_flag,
                test_zipped_doctest.test_Example,
                test_zipped_doctest.test_debug,
                test_zipped_doctest.test_pdb_set_trace,
                test_zipped_doctest.test_pdb_set_trace_nested,
                test_zipped_doctest.test_testsource,
                test_zipped_doctest.test_trailing_space_in_test,
                test_zipped_doctest.test_DocTestSuite,
                test_zipped_doctest.test_DocTestFinder,
            ]
            # These remaining tests are the ones which need access
            # to the data files, so we don't run them
            fail_due_to_missing_data_files = [
                test_zipped_doctest.test_DocFileSuite,
                test_zipped_doctest.test_testfile,
                test_zipped_doctest.test_unittest_reportflags,
            ]
            # Needed for test_DocTestParser and test_debug
            deprecations = [
                # Ignore all warnings about the use of class Tester in this module.
                ("class Tester is deprecated", DeprecationWarning)]
            if sys.py3kwarning:
                deprecations += [
                    ("backquote not supported", SyntaxWarning),
                    ("execfile.. not supported", DeprecationWarning)]
            with test.test_support.check_warnings(*deprecations):
                for obj in known_good_tests:
                    _run_object_doctest(obj, test_zipped_doctest)

Example 36

Project: replaylib
Source File: ez_setup.py
View license
def main(argv, version=DEFAULT_VERSION):
    """Install or upgrade setuptools and EasyInstall"""
    try:
        import setuptools
    except ImportError:
        egg = None
        try:
            egg = download_setuptools(version, delay=0)
            sys.path.insert(0,egg)
            from setuptools.command.easy_install import main
            return main(list(argv)+[egg])   # we're done here
        finally:
            if egg and os.path.exists(egg):
                os.unlink(egg)
    else:
        if setuptools.__version__ == '0.0.1':
            print >>sys.stderr, (
            "You have an obsolete version of setuptools installed.  Please\n"
            "remove it from your system entirely before rerunning this script."
            )
            sys.exit(2)

    req = "setuptools>="+version
    import pkg_resources
    try:
        pkg_resources.require(req)
    except pkg_resources.VersionConflict:
        try:
            from setuptools.command.easy_install import main
        except ImportError:
            from easy_install import main
        main(list(argv)+[download_setuptools(delay=0)])
        sys.exit(0) # try to force an exit
    else:
        if argv:
            from setuptools.command.easy_install import main
            main(argv)
        else:
            print "Setuptools version",version,"or greater has been installed."
            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'

Example 37

Project: django-evolution
Source File: ez_setup.py
View license
def main(argv, version=DEFAULT_VERSION):
    """Install or upgrade setuptools and EasyInstall"""
    try:
        import setuptools
    except ImportError:
        egg = None
        try:
            egg = download_setuptools(version, delay=0)
            sys.path.insert(0,egg)
            from setuptools.command.easy_install import main
            return main(list(argv)+[egg])   # we're done here
        finally:
            if egg and os.path.exists(egg):
                os.unlink(egg)
    else:
        if setuptools.__version__ == '0.0.1':
            print >>sys.stderr, (
            "You have an obsolete version of setuptools installed.  Please\n"
            "remove it from your system entirely before rerunning this script."
            )
            sys.exit(2)

    req = "setuptools>="+version
    import pkg_resources
    try:
        pkg_resources.require(req)
    except pkg_resources.VersionConflict:
        try:
            from setuptools.command.easy_install import main
        except ImportError:
            from easy_install import main
        main(list(argv)+[download_setuptools(delay=0)])
        sys.exit(0) # try to force an exit
    else:
        if argv:
            from setuptools.command.easy_install import main
            main(argv)
        else:
            print "Setuptools version",version,"or greater has been installed."
            print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'

Example 38

Project: imagrium
Source File: test_zipimport_support.py
View license
    @unittest.skipIf(is_jython, "FIXME: not working on Jython")
    def test_doctest_issue4197(self):
        # To avoid having to keep two copies of the doctest module's
        # unit tests in sync, this test works by taking the source of
        # test_doctest itself, rewriting it a bit to cope with a new
        # location, and then throwing it in a zip file to make sure
        # everything still works correctly
        test_src = inspect.getsource(test_doctest)
        test_src = test_src.replace(
                         "from test import test_doctest",
                         "import test_zipped_doctest as test_doctest")
        test_src = test_src.replace("test.test_doctest",
                                    "test_zipped_doctest")
        test_src = test_src.replace("test.sample_doctest",
                                    "sample_zipped_doctest")
        sample_src = inspect.getsource(sample_doctest)
        sample_src = sample_src.replace("test.test_doctest",
                                        "test_zipped_doctest")
        with temp_dir() as d:
            script_name = make_script(d, 'test_zipped_doctest',
                                            test_src)
            zip_name, run_name = make_zip_script(d, 'test_zip',
                                                script_name)
            z = zipfile.ZipFile(zip_name, 'a')
            z.writestr("sample_zipped_doctest.py", sample_src)
            z.close()
            if verbose:
                zip_file = zipfile.ZipFile(zip_name, 'r')
                print 'Contents of %r:' % zip_name
                zip_file.printdir()
                zip_file.close()
            os.remove(script_name)
            sys.path.insert(0, zip_name)
            import test_zipped_doctest
            # Some of the doc tests depend on the colocated text files
            # which aren't available to the zipped version (the doctest
            # module currently requires real filenames for non-embedded
            # tests). So we're forced to be selective about which tests
            # to run.
            # doctest could really use some APIs which take a text
            # string or a file object instead of a filename...
            known_good_tests = [
                test_zipped_doctest.SampleClass,
                test_zipped_doctest.SampleClass.NestedClass,
                test_zipped_doctest.SampleClass.NestedClass.__init__,
                test_zipped_doctest.SampleClass.__init__,
                test_zipped_doctest.SampleClass.a_classmethod,
                test_zipped_doctest.SampleClass.a_property,
                test_zipped_doctest.SampleClass.a_staticmethod,
                test_zipped_doctest.SampleClass.double,
                test_zipped_doctest.SampleClass.get,
                test_zipped_doctest.SampleNewStyleClass,
                test_zipped_doctest.SampleNewStyleClass.__init__,
                test_zipped_doctest.SampleNewStyleClass.double,
                test_zipped_doctest.SampleNewStyleClass.get,
                test_zipped_doctest.old_test1,
                test_zipped_doctest.old_test2,
                test_zipped_doctest.old_test3,
                test_zipped_doctest.old_test4,
                test_zipped_doctest.sample_func,
                test_zipped_doctest.test_DocTest,
                test_zipped_doctest.test_DocTestParser,
                test_zipped_doctest.test_DocTestRunner.basics,
                test_zipped_doctest.test_DocTestRunner.exceptions,
                test_zipped_doctest.test_DocTestRunner.option_directives,
                test_zipped_doctest.test_DocTestRunner.optionflags,
                test_zipped_doctest.test_DocTestRunner.verbose_flag,
                test_zipped_doctest.test_Example,
                test_zipped_doctest.test_debug,
                test_zipped_doctest.test_pdb_set_trace,
                test_zipped_doctest.test_pdb_set_trace_nested,
                test_zipped_doctest.test_testsource,
                test_zipped_doctest.test_trailing_space_in_test,
                test_zipped_doctest.test_DocTestSuite,
                test_zipped_doctest.test_DocTestFinder,
            ]
            # These remaining tests are the ones which need access
            # to the data files, so we don't run them
            fail_due_to_missing_data_files = [
                test_zipped_doctest.test_DocFileSuite,
                test_zipped_doctest.test_testfile,
                test_zipped_doctest.test_unittest_reportflags,
            ]
            # Needed for test_DocTestParser and test_debug
            deprecations = [
                # Ignore all warnings about the use of class Tester in this module.
                ("class Tester is deprecated", DeprecationWarning)]
            if sys.py3kwarning:
                deprecations += [
                    ("backquote not supported", SyntaxWarning),
                    ("execfile.. not supported", DeprecationWarning)]
            with test.test_support.check_warnings(*deprecations):
                for obj in known_good_tests:
                    _run_object_doctest(obj, test_zipped_doctest)

Example 39

Project: canto-next
Source File: plugins.py
View license
def try_plugins(topdir, plugin_default=True, disabled_plugins=[], enabled_plugins=[]):
    p = topdir + "/plugins"
    pinit = p + "/__init__.py"

    if not os.path.exists(p):
        log.info("Creating plugins directory.")
        try:
            os.mkdir(p)
        except Exception as e:
            tb = traceback.format_exc()
            log.error("Exception creating plugin directory")
            log.error("\n" + "".join(tb))
            return
    elif not os.path.isdir(p):
        log.warn("Plugins file is not directory.")
        return

    if not os.path.exists(pinit):
        log.info("Creating plugin __init__.py")
        try:
            f = open(pinit, "w")
            f.close()
        except Exception as e:
            tb = traceback.format_exc()
            log.error("Exception creating plugin __init__.py")
            log.error("\n" + "".join(tb))
            return

    # Add plugin path to front of Python path.
    sys.path.insert(0, topdir)

    all_errors = ""

    # Go ahead and import all .py
    for fname in sorted(os.listdir(p)):
        if fname.endswith(".py") and fname != "__init__.py":
            try:
                proper = fname[:-3]

                if plugin_default:
                    if proper in disabled_plugins:
                        log.info("[plugin] %s - DISABLED" % proper)
                    else:
                        __import__("plugins." + proper)
                        log.info("[plugin] %s" % proper)
                else:
                    if proper in enabled_plugins:
                        __import__("plugins." + proper)
                        log.info("[plugin] %s - ENABLED" % proper)
                    else:
                        log.info("[plugin] %s - DISABLED" % proper)
            except CantoWrongProgramException:
                pass
            except Exception as e:
                tb = traceback.format_exc()
                log.error("Exception importing file %s" % fname)
                nice = "".join(tb)
                all_errors += nice
                log.error(nice)

    if all_errors != "":
        return all_errors

Example 40

Project: setuptools
Source File: test_easy_install.py
View license
    def test_setup_requires_override_nspkg(self):
        """
        Like ``test_setup_requires_overrides_version_conflict`` but where the
        ``setup_requires`` package is part of a namespace package that has
        *already* been imported.
        """

        with contexts.save_pkg_resources_state():
            with contexts.tempdir() as temp_dir:
                foobar_1_archive = os.path.join(temp_dir, 'foo.bar-0.1.tar.gz')
                make_nspkg_sdist(foobar_1_archive, 'foo.bar', '0.1')
                # Now actually go ahead an extract to the temp dir and add the
                # extracted path to sys.path so foo.bar v0.1 is importable
                foobar_1_dir = os.path.join(temp_dir, 'foo.bar-0.1')
                os.mkdir(foobar_1_dir)
                with tarfile_open(foobar_1_archive) as tf:
                    tf.extractall(foobar_1_dir)
                sys.path.insert(1, foobar_1_dir)

                dist = PRDistribution(foobar_1_dir, project_name='foo.bar',
                                      version='0.1')
                working_set.add(dist)

                template = DALS("""\
                    import foo  # Even with foo imported first the
                                # setup_requires package should override
                    import setuptools
                    setuptools.setup(**%r)

                    if not (hasattr(foo, '__path__') and
                            len(foo.__path__) == 2):
                        print('FAIL')

                    if 'foo.bar-0.2' not in foo.__path__[0]:
                        print('FAIL')
                """)

                test_pkg = create_setup_requires_package(
                    temp_dir, 'foo.bar', '0.2', make_nspkg_sdist, template)

                test_setup_py = os.path.join(test_pkg, 'setup.py')

                with contexts.quiet() as (stdout, stderr):
                    try:
                        # Don't even need to install the package, just
                        # running the setup.py at all is sufficient
                        run_setup(test_setup_py, ['--name'])
                    except pkg_resources.VersionConflict:
                        self.fail('Installing setup.py requirements '
                            'caused a VersionConflict')

                assert 'FAIL' not in stdout.getvalue()
                lines = stdout.readlines()
                assert len(lines) > 0
                assert lines[-1].strip() == 'test_pkg'

Example 41

Project: robotframework
Source File: ug2html.py
View license
def create_distribution():
    import re
    from urlparse import urlparse

    dist = os.path.normpath(os.path.join(CURDIR, '..', '..', 'dist'))
    ugpath, version = create_userguide()  # we are in doc/userguide after this
    outdir = os.path.join(dist, 'robotframework-userguide-%s' % version)
    templates = os.path.join(outdir, 'templates')
    libraries = os.path.join(outdir, 'libraries')
    images = os.path.join(outdir, 'images')
    print 'Creating distribution directory ...'

    if os.path.exists(outdir):
        print 'Removing previous user guide distribution'
        shutil.rmtree(outdir)
    elif not os.path.exists(dist):
        os.mkdir(dist)

    print 'Recompiling library docs'
    sys.path.insert(0, os.path.join(CURDIR, '..', 'libraries'))
    import lib2html
    lib2html.create_all()

    for dirname in [outdir, templates, libraries, images]:
        print "Creating output directory '%s'" % dirname
        os.mkdir(dirname)

    def replace_links(res):
        if not res.group(5):
            return res.group(0)
        scheme, _, path, _, _, fragment = urlparse(res.group(5))
        if scheme or (fragment and not path):
            return res.group(0)
        replaced_link = '%s %s="%%s/%s"' % (res.group(1), res.group(4),
                                            os.path.basename(path))
        if path.startswith('../../templates'):
            copy(path, templates)
            replaced_link = replaced_link % 'templates'
        elif path.startswith('../libraries'):
            copy(path, libraries)
            replaced_link = replaced_link % 'libraries'
        elif path.startswith('src/'):
            copy(path, images)
            replaced_link = replaced_link % 'images'
        else:
            raise ValueError('Invalid link target: %s (context: %s)'
                             % (path, res.group(0)))
        print "Modified link '%s' -> '%s'" % (res.group(0), replaced_link)
        return replaced_link

    def copy(source, dest):
        print "Copying '%s' -> '%s'" % (source, dest)
        shutil.copy(source, dest)

    link_regexp = re.compile('''
(<(a|img)\s+.*?)
(\s+(href|src)="(.*?)"|>)
''', re.VERBOSE | re.DOTALL | re.IGNORECASE)

    with open(ugpath) as infile:
        content = link_regexp.sub(replace_links, infile.read())
    with open(os.path.join(outdir, os.path.basename(ugpath)), 'wb') as outfile:
        outfile.write(content)
    print os.path.abspath(outfile.name)
    return outdir

Example 42

Project: django-extras
Source File: runner.py
View license
def main():
    """
    The entry point for the script. This script is fairly basic. Here is a
    quick example of how to use it::

        app_test_runner.py [path-to-app]

    You must have Django on the PYTHONPATH prior to running this script. This
    script basically will bootstrap a Django environment for you.

    By default this script with use SQLite and an in-memory database. If you
    are using Python 2.6 it will just work out of the box for you.
    """
    parser = OptionParser()
    parser.add_option("--DATABASE_ENGINE", dest="DATABASE_ENGINE", default="django.db.backends.sqlite3")
    parser.add_option("--DATABASE_NAME", dest="DATABASE_NAME", default=":memory:")
    parser.add_option("--DATABASE_USER", dest="DATABASE_USER", default="")
    parser.add_option("--DATABASE_PASSWORD", dest="DATABASE_PASSWORD", default="")
    parser.add_option("--SITE_ID", dest="SITE_ID", type="int", default=1)

    options, args = parser.parse_args()

    # check for app in args
    try:
        app_path = args[0]
    except IndexError:
        print("You did not provide an app path.")
        raise SystemExit
    else:
        if app_path.endswith("/"):
            app_path = app_path[:-1]
        parent_dir, app_name = os.path.split(app_path)
        sys.path.insert(0, parent_dir)

    settings.configure(**{
        "DATABASES": {
            'default': {
                'ENGINE': options.DATABASE_ENGINE,
                'NAME': options.DATABASE_NAME,  # ':memory:',
                'USER': options.DATABASE_USER,
                'PASSWORD': options.DATABASE_PASSWORD,
                'HOST': '',
                'PORT': '',
            }
        },
        # "SITE_ID": options.SITE_ID,
        "SECRET_KEY": "Test Key",
        "ROOT_URLCONF": "django_app_test.urls",
        "TEMPLATE_LOADERS": (
            "django.template.loaders.app_directories.Loader",
        ),
        "TEMPLATE_DIRS": tuple(),
        "INSTALLED_APPS": (
            "django.contrib.auth",
            "django.contrib.contenttypes",
            "django.contrib.sessions",
            # "django.contrib.sites",
            app_name,
        ),

        # Force test runner to be the pre django 1.6 test runner. This tool does not work with then new default in 1.6.
        "TEST_RUNNER": "django.test.simple.DjangoTestSuiteRunner"
    })

    # This is to ensure that Django 1.7's app registry is populated prior to calling a command.
    if hasattr(django, 'setup'):
        django.setup()

    call_command("test", app_name)

Example 43

View license
    def __init__(self):
        sys.path.insert(0, "../../")
        load_prc_file_data("", "win-size 512 512")
        load_prc_file_data("", "textures-power-2 none")
        load_prc_file_data("", "print-pipe-types #f")
        load_prc_file_data("", "notify-level-glgsg error")
        # load_prc_file_data("", "win-size 1024 1024")

        from rpcore import RenderPipeline, PointLight

        self.render_pipeline = RenderPipeline()
        self.render_pipeline.mount_mgr.config_dir = "config/"
        self.render_pipeline.create(self)

        sphere = self.loader.loadModel("res/sphere.bam")
        sphere.reparent_to(self.render)

        self.disableMouse()
        self.camLens.setFov(40)
        self.camLens.setNearFar(0.03, 2000.0)
        self.camera.set_pos(0, -3.5, 0)
        self.camera.look_at(0, -2.5, 0)

        self.render2d.hide()
        self.aspect2d.hide()

        light = PointLight()
        light.pos = 10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        light = PointLight()
        light.pos = -10, -10, 10
        light.radius = 1e20
        light.color = (1, 1, 1)
        light.inner_radius = 4.0
        light.energy = 3
        self.render_pipeline.add_light(light)

        for mat in sphere.find_all_materials():
            mat.roughness = material.roughness
            mat.base_color = Vec4(*(list(material.basecolor) + [1]))
            mat.refractive_index = material.ior

            mat.metallic = 1.0 if material.mat_type == "metallic" else 0.0

            if material.mat_type == "clearcoat":
                mat.emission = (2, 0, 0, 0)
                mat.metallic = 1.0
                mat.refractive_index = 1.51

            if material.mat_type == "foliage":
                mat.emission = (5, 0, 0, 0)
                mat.metallic = 0.0
                mat.refractive_index = 1.51

        for i in range(10):
            self.taskMgr.step()

        self.win.save_screenshot("scene-rp.png")

        self.accept("r", self.reload)

Example 44

Project: python2-trepan
Source File: helper.py
View license
def run_debugger(testname, python_file, dbgr_opts='', args='',
                 outfile=None):
    datadir   = os.path.join(srcdir, '..', 'data')
    progdir   = os.path.join(srcdir, '..', 'example')
    dbgrdir   = os.path.join(srcdir, '..', '..', 'trepan')
    dbgr_short= "cli.py"
    dbgr_path = os.path.join(dbgrdir, dbgr_short)

    rightfile = os.path.join(datadir, "%s.right" % testname)

    sys.path.insert(0, os.path.join(srcdir, '..', '..'))
    os.environ['PYTHONPATH'] = os.pathsep.join(sys.path)
    cmdfile     = os.path.join(datadir, "%s.cmd"   % testname)
    outfile     = os.path.join(srcdir, "%s.out" % testname)
    if python_file:
        programfile = os.path.join(progdir, python_file)
    else:
        programfile = ''
        pass

    outfile_opt = '--output=%s ' % outfile

    if os.path.exists(outfile): os.unlink(outfile)

    cmd = "%s --command %s %s %s %s %s" % \
          (dbgr_path, cmdfile, outfile_opt, dbgr_opts, programfile, args)

    print(cmd)
    os.system(cmd)
    fromfile  = rightfile
    fromdate  = time.ctime(os.stat(fromfile).st_mtime)
    tofile    = outfile
    todate    = time.ctime(os.stat(tofile).st_mtime)
    with open(fromfile) as f: fromlines = f.readlines()
    with open(tofile) as f: tolines = f.readlines()

    # Filter out last instruction. For example:
    # (gcd.py:11 @6): -> (gcd.py:11)
    tolines = [re.sub(' @\d+\):', '):', line) for line in tolines]

    diff = list(difflib.unified_diff(fromlines, tolines, fromfile,
                                     tofile, fromdate, todate))
    if len(diff) == 0:
        os.unlink(outfile)
        pass
    else:
        with open(tofile, 'w') as out:
            out.writelines(tolines)
            pass
        pass
    for line in diff:
        print(line.rstrip())
        pass
    return len(diff) == 0

Example 45

Project: whirlwind
Source File: whirlwind-admin.py
View license
def main():

    usage = "usage: %prog [options [args]]"
    parser = optparse.OptionParser(usage)

    parser.add_option("--ca", "--create-application",
                    dest="create_app",
                    metavar="FILE",
                    action="store_true",
                    default=False,
                    help="Creates an application structure")

    parser.add_option("--v", "--version", dest="version",
                    action="store_true",
                    default=False,
                    help="Print the version info for this release of WhirlWind")

    parser.add_option("--gcs", "--generate-cookie-secret", dest="generate_cookie_secret",
                    action="store_true",
                    default=False,
                    help="Generate a cookie secret hash")

    parser.add_option("--gmi", "--generate-model-indexes", dest="generate_model_indexes",
                action="store_true",
                default=False,
                help="Generate mongo indexes for your models")

    options, args = parser.parse_args()

    if not options.create_app and not options.version and not options.generate_cookie_secret and not options.generate_model_indexes:
        parser.error('Must choose one -- try --ca or --v or --gcs or --gmi')

    if options.create_app:

        if len(args) != 1:
            logging.error("Error no app name given")
            return

        #generate the template dir path
        template_dir = os.path.join(whirlwind.__path__[0], 'conf', 'app_template')

        #copy the template files
        copied_files = dir_util.copy_tree(template_dir, args[0])

        #check that we copied files
        if len(copied_files) > 0:
            logging.info('Created %s' % options.create_app)
        else:
            logging.info('Error copying app template')

    if options.version:
        logging.info(whirlwind.get_version())

    if options.generate_cookie_secret:
        import base64
        import uuid
        print(base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes))

    if options.generate_model_indexes:

        import sys
        import pkgutil
        from whirlwind.db.mongo import Mongo

        #insert the current dir into the path
        sys.path.insert(0, os.getcwd())

        #grab a settings path from our args if exists or assume relative default
        settings_module = args[0] if len(args) == 1 else 'config.settings'

        conf = __import__(settings_module)

        #connect to our db using our options set in settings.py
        Mongo.create(host=conf.settings.db_host, port=conf.settings.db_port)

        #import our default models package
        __import__('application.models')

        pkg_mods = sys.modules['application.models']

        #setup a prefix string
        prefix = pkg_mods.__name__ + "."

        #import all the modules in the models dir so the registration decorators fire
        for importer, modname, ispkg in pkgutil.iter_modules(pkg_mods.__path__, prefix):
            __import__(modname)

        #loop over the registered documents
        for doc, obj in Mongo.db.connection._registered_documents.iteritems():
            try:

                print 'Attempting to create index for ', doc
                #generate the index for this doc on the collection
                obj.generate_index(Mongo.db.connection[conf.settings.db_name][obj._obj_class.__collection__])
            except Exception, e:
                #barf up an error on fail
                print 'Could not create index for %s - exception: %s' % (doc, e.message)

Example 46

Project: PokemonGo-Bot-Desktop
Source File: runpy.py
View license
def run_path(path_name, init_globals=None, run_name=None):
    """Execute code located at the specified filesystem location

       Returns the resulting top level namespace dictionary

       The file path may refer directly to a Python script (i.e.
       one that could be directly executed with execfile) or else
       it may refer to a zipfile or directory containing a top
       level __main__.py script.
    """
    if run_name is None:
        run_name = "<run_path>"
    importer = _get_importer(path_name)
    if isinstance(importer, imp.NullImporter):
        # Not a valid sys.path entry, so run the code directly
        # execfile() doesn't help as we want to allow compiled files
        code = _get_code_from_file(path_name)
        return _run_module_code(code, init_globals, run_name, path_name)
    else:
        # Importer is defined for path, so add it to
        # the start of sys.path
        sys.path.insert(0, path_name)
        try:
            # Here's where things are a little different from the run_module
            # case. There, we only had to replace the module in sys while the
            # code was running and doing so was somewhat optional. Here, we
            # have no choice and we have to remove it even while we read the
            # code. If we don't do this, a __loader__ attribute in the
            # existing __main__ module may prevent location of the new module.
            main_name = "__main__"
            saved_main = sys.modules[main_name]
            del sys.modules[main_name]
            try:
                mod_name, loader, code, fname = _get_main_module_details()
            finally:
                sys.modules[main_name] = saved_main
            pkg_name = ""
            with _TempModule(run_name) as temp_module, \
                 _ModifiedArgv0(path_name):
                mod_globals = temp_module.module.__dict__
                return _run_code(code, mod_globals, init_globals,
                                    run_name, fname, loader, pkg_name).copy()
        finally:
            try:
                sys.path.remove(path_name)
            except ValueError:
                pass

Example 47

Project: asyncflux
Source File: runtests.py
View license
def main():
    my_dir = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, os.path.abspath(os.path.join(my_dir, '..')))

    from optparse import OptionParser
    parser = OptionParser()
    parser.add_option('--with-pep8', action='store_true', dest='with_pep8',
                      default=True)
    parser.add_option('--with-pyflakes', action='store_true',
                      dest='with_pyflakes', default=True)
    parser.add_option('--force-all', action='store_true', dest='force_all',
                      default=False)
    parser.add_option('-v', '--verbose', action='count', dest='verbosity',
                      default=0)
    parser.add_option('-q', '--quiet', action='count', dest='quietness',
                      default=0)
    options, extra_args = parser.parse_args()
    has_pep8 = False
    try:
        import pep8
        has_pep8 = True
    except ImportError:
        if options.with_pep8:
            sys.stderr.write('# Could not find pep8 library.')
            sys.exit(1)

    if has_pep8:
        guide_main = pep8.StyleGuide(
            ignore=['E402'],
            paths=['asyncflux/'],
            exclude=[],
            max_line_length=80,
        )
        guide_tests = pep8.StyleGuide(
            ignore=['E221'],
            paths=['tests/'],
            max_line_length=80,
        )
        for guide in (guide_main, guide_tests):
            report = guide.check_files()
            if report.total_errors:
                sys.exit(1)

    if options.with_pyflakes:
        try:
            import pyflakes
            assert pyflakes  # silence pyflakes
        except ImportError:
            sys.stderr.write('# Could not find pyflakes library.\n')
            sys.exit(1)

        from pyflakes import api, reporter
        warnings = api.checkRecursive(['asyncflux', 'tests'],
                                      reporter._makeDefaultReporter())
        if warnings > 0:
            sys.exit(1)

    suite = make_suite('', tuple(extra_args), options.force_all)

    runner = TextTestRunner(verbosity=options.verbosity - options.quietness + 1)
    result = runner.run(suite)
    sys.exit(not result.wasSuccessful())

Example 48

Project: Yarn
Source File: yarn.py
View license
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--hosts', '-H', type=parse_host_list,
                        help="Host(s) separated by commas.")
    parser.add_argument('--user', '-U', type=str,
                        help="Username to use for connecting, defaults to current username.")
    parser.add_argument('--parallel', '-P', dest="parallel", action="store_true",
                        help="Run commands in parallel.",
                        default=False)
    parser.add_argument('--port', '-p', dest="port", type=int,
                        help="What port to use for connecting to the remote host. Defaults to 22",
                        default=22)
    parser.add_argument('--yarn-file', '-f', type=parse_yarn_file_path,
                        help="Yarn file to use, defaults to yarnfile.py.",
                        default="./yarnfile.py")
    parser.add_argument('--warn-only', '-w', action="store_true", dest="warn_only",
                        help="Do not halt upon finding an error.",
                        default=False)
    parser.add_argument('--quiet', '-q', action="store_true", dest="quiet",
                        help="Suppress extra output.",
                        default=False)
    parser.add_argument(dest='commands', nargs=argparse.REMAINDER)

    args = parser.parse_args()
    tasks = dict()
    if os.path.isfile(args.yarn_file):
        directory, yarnfile = os.path.split(os.path.abspath(args.yarn_file))
        sys.path.insert(0, directory)
        tasks = vars(__import__(yarnfile.split(".")[0]))

    if args.user:
        env.user = args.user
    env.quiet = args.quiet
    env.warn_only = args.warn_only
    env.run_parallel = args.parallel
    if args.hosts:
        for host in args.hosts:
            env.host_string = host
            if "@" in host:
                # This is to handle the ability to have [email protected] on the command line
                env.user, env.host_string = host.split("@")
            if ":" in env.host_string:
                # This is to handle the ability to have hostname:port on the command line
                host_string, port = env.host_string.split(":")
                env.host_string = host_string
                env.port = int(port)
            for command in args.commands:
                execute_task(tasks, command)
    else:
        for command in args.commands:
            execute_task(tasks, command)

Example 49

Project: python3-trepan
Source File: helper.py
View license
def run_debugger(testname, python_file, dbgr_opts='', args='',
                 outfile=None):
    datadir   = os.path.join(srcdir, '..', 'data')
    progdir   = os.path.join(srcdir, '..', 'example')
    dbgrdir   = os.path.join(srcdir, '..', '..', 'trepan')
    dbgr_short= "cli.py"
    dbgr_path = os.path.join(dbgrdir, dbgr_short)

    rightfile = os.path.join(datadir, "%s.right" % testname)

    sys.path.insert(0, os.path.join(srcdir, '..', '..'))
    os.environ['PYTHONPATH'] = os.pathsep.join(sys.path)
    cmdfile     = os.path.join(datadir, "%s.cmd"   % testname)
    outfile     = os.path.join(srcdir, "%s.out" % testname)
    if python_file:
        programfile = os.path.join(progdir, python_file)
    else:
        programfile = ''
        pass

    outfile_opt = '--output=%s ' % outfile

    if os.path.exists(outfile): os.unlink(outfile)

    cmd = "%s --command %s %s %s %s %s" % \
          (dbgr_path, cmdfile, outfile_opt, dbgr_opts, programfile, args)

    # print(cmd)
    os.system(cmd)
    fromfile  = rightfile
    fromdate  = time.ctime(os.stat(fromfile).st_mtime)
    tofile    = outfile
    todate    = time.ctime(os.stat(tofile).st_mtime)
    with open(fromfile) as f: fromlines = f.readlines()
    with open(tofile) as f: tolines = f.readlines()

    # Filter out last instruction. For example:
    # (gcd.py:11 @6): -> (gcd.py:11)
    tolines = [re.sub(' @\d+\):', '):', line) for line in tolines]

    diff = list(difflib.unified_diff(fromlines, tolines, fromfile,
                                     tofile, fromdate, todate))
    if len(diff) == 0:
        os.unlink(outfile)
        pass
    else:
        with open(tofile, 'w') as out:
            out.writelines(tolines)
            pass
        pass
    for line in diff:
        print(line.rstrip())
        pass
    return len(diff) == 0

Example 50

View license
    def test_doctest_issue4197(self):
        # To avoid having to keep two copies of the doctest module's
        # unit tests in sync, this test works by taking the source of
        # test_doctest itself, rewriting it a bit to cope with a new
        # location, and then throwing it in a zip file to make sure
        # everything still works correctly
        test_src = inspect.getsource(test_doctest)
        test_src = test_src.replace(
                         "from test import test_doctest",
                         "import test_zipped_doctest as test_doctest")
        test_src = test_src.replace("test.test_doctest",
                                    "test_zipped_doctest")
        test_src = test_src.replace("test.sample_doctest",
                                    "sample_zipped_doctest")
        sample_src = inspect.getsource(sample_doctest)
        sample_src = sample_src.replace("test.test_doctest",
                                        "test_zipped_doctest")
        with temp_dir() as d:
            script_name = make_script(d, 'test_zipped_doctest',
                                            test_src)
            zip_name, run_name = make_zip_script(d, 'test_zip',
                                                script_name)
            z = zipfile.ZipFile(zip_name, 'a')
            z.writestr("sample_zipped_doctest.py", sample_src)
            z.close()
            if verbose:
                zip_file = zipfile.ZipFile(zip_name, 'r')
                print ('Contents of %r:' % zip_name)
                zip_file.printdir()
                zip_file.close()
            os.remove(script_name)
            sys.path.insert(0, zip_name)
            import test_zipped_doctest
            try:
                # Some of the doc tests depend on the colocated text files
                # which aren't available to the zipped version (the doctest
                # module currently requires real filenames for non-embedded
                # tests). So we're forced to be selective about which tests
                # to run.
                # doctest could really use some APIs which take a text
                # string or a file object instead of a filename...
                known_good_tests = [
                    test_zipped_doctest.SampleClass,
                    test_zipped_doctest.SampleClass.NestedClass,
                    test_zipped_doctest.SampleClass.NestedClass.__init__,
                    test_zipped_doctest.SampleClass.__init__,
                    test_zipped_doctest.SampleClass.a_classmethod,
                    test_zipped_doctest.SampleClass.a_property,
                    test_zipped_doctest.SampleClass.a_staticmethod,
                    test_zipped_doctest.SampleClass.double,
                    test_zipped_doctest.SampleClass.get,
                    test_zipped_doctest.SampleNewStyleClass,
                    test_zipped_doctest.SampleNewStyleClass.__init__,
                    test_zipped_doctest.SampleNewStyleClass.double,
                    test_zipped_doctest.SampleNewStyleClass.get,
                    test_zipped_doctest.sample_func,
                    test_zipped_doctest.test_DocTest,
                    test_zipped_doctest.test_DocTestParser,
                    test_zipped_doctest.test_DocTestRunner.basics,
                    test_zipped_doctest.test_DocTestRunner.exceptions,
                    test_zipped_doctest.test_DocTestRunner.option_directives,
                    test_zipped_doctest.test_DocTestRunner.optionflags,
                    test_zipped_doctest.test_DocTestRunner.verbose_flag,
                    test_zipped_doctest.test_Example,
                    test_zipped_doctest.test_debug,
                    test_zipped_doctest.test_pdb_set_trace,
                    test_zipped_doctest.test_pdb_set_trace_nested,
                    test_zipped_doctest.test_testsource,
                    test_zipped_doctest.test_trailing_space_in_test,
                    test_zipped_doctest.test_DocTestSuite,
                    test_zipped_doctest.test_DocTestFinder,
                ]
                # These remaining tests are the ones which need access
                # to the data files, so we don't run them
                fail_due_to_missing_data_files = [
                    test_zipped_doctest.test_DocFileSuite,
                    test_zipped_doctest.test_testfile,
                    test_zipped_doctest.test_unittest_reportflags,
                ]
                for obj in known_good_tests:
                    _run_object_doctest(obj, test_zipped_doctest)
            finally:
                del sys.modules["test_zipped_doctest"]