Python sys.exec_prefix() Examples

The following are 30 code examples of sys.exec_prefix(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sys , or try the search function .
Example #1
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_whitespace():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("")
    ipi.End()
    
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("2")
    Assert("2" in response)
    ipi.End()
    
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("  ")
    response = ipi.ExecuteLine("  2", True)
    Assert("SyntaxError:" in response)
    ipi.End()


###########################################################
# test the indentation error in the interactive mode 
Example #2
Source File: test_stdconsole.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_S(self):
        """Test the -S (suppress site initialization) option."""

        # Create a local site.py that sets some global context. Do this in a temporary directory to avoid accidently
        # overwriting a real site.py or creating confusion. Use the IRONPYTHONPATH environment variable to point
        # IronPython at this version of site.py.
        from System import Environment
        with open(os.path.join(self.tmpdir, "site.py"), "w") as f:
            f.write("import sys\nsys.foo = 123\n")
        
        with IronPythonVariableContext("IRONPYTHONPATH", self.tmpdir, prepend=True):
            print(Environment.GetEnvironmentVariable("IRONPYTHONPATH"))
            # Verify that the file gets loaded by default.
            self.TestCommandLine(("-c", "import sys; print(sys.foo)"), "123\n")
            
            # CP778 - verify 'site' does not show up in dir()
            self.TestCommandLine(("-c", "print('site' in dir())"), "False\n")
            
            # Verify that Lib remains in sys.path.
            self.TestCommandLine(("-S", "-c", "import os ; import sys; print(str(os.path.join(sys.exec_prefix, 'Lib')).lower() in [x.lower() for x in sys.path])"), "True\n")
            
            # Now check that we can suppress this with -S.
            self.TestCommandLine(("-S", "-c", "import sys; print(sys.foo)"), ("lastline", "AttributeError: 'module' object has no attribute 'foo'\n"), 1) 
Example #3
Source File: method.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_from_cmdline():
    '''
    '''
    from iptest.console_util import IronPythonInstance
    from sys import executable, exec_prefix
    from System import Environment
    
    extraArgs = ""
    if "-X:PreferComInteropAssembly" in Environment.GetCommandLineArgs():
        extraArgs += "-X:PreferComInteropAssembly"
        
    #Does it work from the commandline with positive cases?
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    try:
        ipi.ExecuteLine("from System import Type, Activator")
        ipi.ExecuteLine("com_obj = Activator.CreateInstance(Type.GetTypeFromProgID('DlrComLibrary.DlrUniversalObj'))")
        
        #Dev10 409941    
        Assert("System.__ComObject" in ipi.ExecuteLine("print com_obj"))            
        AreEqual(ipi.ExecuteLine("print com_obj.m0()"), "None")
    finally:
        ipi.End() 
Example #4
Source File: test_dynamic_regressions.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_cp20519(self):
        import os
        import System

        cp20519_vb_filename = os.path.join(self.temporary_dir, "cp20519_vb_module.vb")
        f = open(cp20519_vb_filename, "w")
        f.writelines(cp20519_vb_snippet)
        f.close()

        cp20519_vb_exename  = os.path.join(self.temporary_dir, "cp20519_vb.exe")
        compile_cmd = "/target:exe /out:%s %s /reference:%s /reference:%s /reference:%s" % (cp20519_vb_exename,
                                                                            cp20519_vb_filename,
                                                                            os.path.join(sys.exec_prefix, "IronPython.dll"),
                                                                            os.path.join(sys.exec_prefix, "Microsoft.Scripting.dll"),
                                                                            os.path.join(sys.exec_prefix, "Microsoft.Dynamic.dll"))
        self.assertEqual(self.run_vbc(compile_cmd), 0)
        for x in ["IronPython.dll", "Microsoft.Scripting.dll", "Microsoft.Dynamic.dll"]:
            System.IO.File.Copy(os.path.join(sys.exec_prefix, x), os.path.join(self.temporary_dir, x), True)

        self.assertEqual(os.system(cp20519_vb_exename), 0)
        os.remove(cp20519_vb_exename)
        os.remove(cp20519_vb_filename) 
Example #5
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_ipy_dash_m_pkgs(): 
    # Python packages work
    import nt
    Assert("testpkg1" in [x.lower() for x in nt.listdir(nt.getcwd())], nt.getcwd())
    
    old_ipy_path = get_environ_variable("IRONPYTHONPATH")
    try:
        nt.environ["IRONPYTHONPATH"] = nt.getcwd()
        ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 0)   # should have returned 0
        AreEqual(output, "")
    
        # Bad module names should not work
        ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m libxyz")
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(res, True) # run should have worked
        AreEqual(exit, 1)   # should have returned 0
        Assert("ImportError: No module named libxyz" in err,
               "stderr is:" + str(err))
    finally:
        nt.environ["IRONPYTHONPATH"] = old_ipy_path 
Example #6
Source File: test_sysconfig.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_user_similar(self):
        # Issue #8759: make sure the posix scheme for the users
        # is similar to the global posix_prefix one
        base = get_config_var('base')
        user = get_config_var('userbase')
        # the global scheme mirrors the distinction between prefix and
        # exec-prefix but not the user scheme, so we have to adapt the paths
        # before comparing (issue #9100)
        adapt = sys.prefix != sys.exec_prefix
        for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
            global_path = get_path(name, 'posix_prefix')
            if adapt:
                global_path = global_path.replace(sys.exec_prefix, sys.prefix)
                base = base.replace(sys.exec_prefix, sys.prefix)
            user_path = get_path(name, 'posix_user')
            self.assertEqual(user_path, global_path.replace(base, user, 1)) 
Example #7
Source File: test_importpkg.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_c1cs(self):
        """verify re-loading an assembly causes the new type to show up"""
        if not self.has_csc():
            return
        
        c1cs = get_local_filename('c1.cs')
        outp = sys.exec_prefix
        
        self.compileAndRef('c1', c1cs, '/d:BAR1')
        
        import Foo
        class c1Child(Foo.Bar): pass
        o = c1Child()
        self.assertEqual(o.Method(), "In bar1")
        
        
        self.compileAndRef('c1_b', c1cs)
        import Foo
        class c2Child(Foo.Bar): pass
        o = c2Child()
        self.assertEqual(o.Method(), "In bar2")
        # ideally we would delete c1.dll, c2.dll here so as to keep them from cluttering up
        # /Public; however, they need to be present for the peverify pass.

    #TODO: @skip("multiple_execute") 
Example #8
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_exceptions_nested():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)

    ipi.ExecutePartialLine("def a(): return b()")
    ipi.ExecuteLine("")
    ipi.ExecutePartialLine("def b(): return 1/0")
    ipi.ExecuteLine("")
    response = ipi.ExecuteLine("a()", True)
    response = response.replace("\r\r\n", "\n").strip()
    Assert(response.startswith('''Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in a
  File "<stdin>", line 1, in b
ZeroDivisionError:'''), response)
            
    ipi.End()


###############################################################################
# Test "ipy.exe -i script.py" 
Example #9
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_exception_slicing_warning():
    ipi = IronPythonInstance(executable, exec_prefix, '-c "print Exception(*range(2))[1]"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '1\r\n')   # some std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 0)     # should return 0
    
    ipi = IronPythonInstance(executable, exec_prefix,
        '-3 -c "import warnings;'
        'warnings.filters.reverse();'
        'warnings.filters.pop();'
        'print Exception(*range(2))[1]"')
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '1\r\n')   # std out
    Assert(res[2].endswith('DeprecationWarning: __getitem__ not supported for exception classes in 3.x; use args attribute\r\n')) #std err
    AreEqual(res[3], 0)     # should return 0

#------------------------------------------------------------------------------ 
Example #10
Source File: run_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def __init__(self, fileName):
        scriptEnv = Python.CreateRuntime()
        self.fileName = fileName
        self.engine = scriptEnv.GetEngine("python")        
        self.context = HostingHelpers.GetLanguageContext(self.engine) 
        scriptEnv.LoadAssembly(Type.GetType("System.String").Assembly) #mscorlib.dll
        scriptEnv.LoadAssembly(UriBuilder().GetType().Assembly)  #System.dll
                
        self.InitializePath()
        
        executable = Assembly.GetEntryAssembly().Location
        prefix = Path.GetDirectoryName(executable)
        
        self.context.SystemState.executable = executable
        self.context.SystemState.exec_prefix = self.context.SystemState.prefix = prefix
        
        import imp
        mod = imp.new_module('__main__')
        mod.__file__ = fileName
        mod.__builtins__ = sys.modules['__builtin__']
        self.context.SystemState.modules['__main__'] = mod
        self.mainScope = scriptEnv.CreateScope(mod.__dict__) 
Example #11
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_console_input_output():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    input_output = [
    ("x=100",""),
    ("x=200\n",""),
    ("\nx=300",""),
    ("\nx=400\n",""),
    ("500","500"),
    ("600\n\n\n\n\n\n\n\n\n\n\n","600"),
    ("valid=3;more_valid=4;valid","3"),
    ("valid=5;more_valid=6;more_valid\n\n\n\n\n","6"),
    ("valid=7;more_valid=8;#valid",""),
    ("valid=9;valid;# more_valid\n","9"),
    ("valid=11;more_valid=12;more_valid# should be valid input\n\n\n\n","12"),
    ]
    
    
    for x in input_output:
        AreEqual(ipi.Start(), True)
        AreEqual(ipi.ExecuteLine(x[0]),x[1])
        ipi.End()
    
# expect a clean exception message/stack from thread 
Example #12
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_globals8961():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    
    response = ipi.ExecuteLine("print globals().keys()")
    res = set(eval(response))
    AreEqual(res, set(['__builtins__', '__name__', '__doc__']))
    
    ipi.ExecuteLine("a = None")
    response = ipi.ExecuteLine("print globals().keys()")
    res = set(eval(response))
    AreEqual(res, set(['__builtins__', '__name__', '__doc__', 'a']))
    response = ipi.ExecuteLine("print globals().values()")
    l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"'))
    res = set(l)
    AreEqual(len(l), 4)
    AreEqual(res, set(['builtin', '__main__', None]))
    
    ipi.ExecuteLine("b = None")
    response = ipi.ExecuteLine("print globals().values()")
    l = eval(response.replace("<module '__builtin__' (built-in)>", '"builtin"'))
    res = set(l)
    AreEqual(len(l), 5)
    AreEqual(res, set(['builtin', '__main__', None])) 
Example #13
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_incomplate_syntax_backslash():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
       
    for i in xrange(4):
        for j in xrange(i):
            ipi.ExecutePartialLine("\\")
        ipi.ExecutePartialLine("1 + \\")
        for j in xrange(i):
            ipi.ExecutePartialLine("\\")
        response = ipi.ExecuteLine("2", True)
        Assert("3" in response)
    
    ipi.End()

###########################################################
# if , while, try, for and then EOF. 
Example #14
Source File: test_sysconfig.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_user_similar(self):
        # Issue #8759: make sure the posix scheme for the users
        # is similar to the global posix_prefix one
        base = get_config_var('base')
        user = get_config_var('userbase')
        # the global scheme mirrors the distinction between prefix and
        # exec-prefix but not the user scheme, so we have to adapt the paths
        # before comparing (issue #9100)
        adapt = sys.prefix != sys.exec_prefix
        for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
            global_path = get_path(name, 'posix_prefix')
            if adapt:
                global_path = global_path.replace(sys.exec_prefix, sys.prefix)
                base = base.replace(sys.exec_prefix, sys.prefix)
            user_path = get_path(name, 'posix_user')
            self.assertEqual(user_path, global_path.replace(base, user, 1)) 
Example #15
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_comments():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    
    response = ipi.ExecuteLine("# this is some comment line")
    AreEqual(response, "")
    response = ipi.ExecuteLine("    # this is some comment line")
    AreEqual(response, "")
    response = ipi.ExecuteLine("# this is some more comment line")
    AreEqual(response, "")
    ipi.ExecutePartialLine("if 100:")
    ipi.ExecutePartialLine("    print 100")
    ipi.ExecutePartialLine("# this is some more comment line inside if")
    ipi.ExecutePartialLine("#     this is some indented comment line inside if")
    ipi.ExecutePartialLine("    print 200")
    response = ipi.ExecuteLine("")
    AreEqual(response, "100" + newline + "200")
    ipi.End() 
Example #16
Source File: install.py    From BinderFilter with MIT License 5 votes vote down vote up
def finalize_unix (self):

        if self.install_base is not None or self.install_platbase is not None:
            if ((self.install_lib is None and
                 self.install_purelib is None and
                 self.install_platlib is None) or
                self.install_headers is None or
                self.install_scripts is None or
                self.install_data is None):
                raise DistutilsOptionError, \
                      ("install-base or install-platbase supplied, but "
                      "installation scheme is incomplete")
            return

        if self.user:
            if self.install_userbase is None:
                raise DistutilsPlatformError(
                    "User base directory is not specified")
            self.install_base = self.install_platbase = self.install_userbase
            self.select_scheme("unix_user")
        elif self.home is not None:
            self.install_base = self.install_platbase = self.home
            self.select_scheme("unix_home")
        else:
            if self.prefix is None:
                if self.exec_prefix is not None:
                    raise DistutilsOptionError, \
                          "must not supply exec-prefix without prefix"

                self.prefix = os.path.normpath(sys.prefix)
                self.exec_prefix = os.path.normpath(sys.exec_prefix)

            else:
                if self.exec_prefix is None:
                    self.exec_prefix = self.prefix

            self.install_base = self.prefix
            self.install_platbase = self.exec_prefix
            self.select_scheme("unix_prefix")

    # finalize_unix () 
Example #17
Source File: sysconfig.py    From BinderFilter with MIT License 5 votes vote down vote up
def get_config_vars(*args):
    """With no arguments, return a dictionary of all configuration
    variables relevant for the current platform.  Generally this includes
    everything needed to build extensions and install both pure modules and
    extensions.  On Unix, this means every variable defined in Python's
    installed Makefile; on Windows and Mac OS it's a much smaller set.

    With arguments, return a list of values that result from looking up
    each argument in the configuration variable dictionary.
    """
    global _config_vars
    if _config_vars is None:
        func = globals().get("_init_" + os.name)
        if func:
            func()
        else:
            _config_vars = {}

        # Normalized versions of prefix and exec_prefix are handy to have;
        # in fact, these are the standard versions used most places in the
        # Distutils.
        _config_vars['prefix'] = PREFIX
        _config_vars['exec_prefix'] = EXEC_PREFIX

        # OS X platforms require special customization to handle
        # multi-architecture, multi-os-version installers
        if sys.platform == 'darwin':
            import _osx_support
            _osx_support.customize_config_vars(_config_vars)

    if args:
        vals = []
        for name in args:
            vals.append(_config_vars.get(name))
        return vals
    else:
        return _config_vars 
Example #18
Source File: sysconfig.py    From BinderFilter with MIT License 5 votes vote down vote up
def get_python_inc(plat_specific=0, prefix=None):
    """Return the directory containing installed Python header files.

    If 'plat_specific' is false (the default), this is the path to the
    non-platform-specific header files, i.e. Python.h and so on;
    otherwise, this is the path to platform-specific header files
    (namely pyconfig.h).

    If 'prefix' is supplied, use it instead of sys.prefix or
    sys.exec_prefix -- i.e., ignore 'plat_specific'.
    """
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    # GCC(mingw): os.name is "nt" but build system is posix
    if os.name == "posix" or sys.version.find('GCC') >= 0:
        if python_build:
            # NOTE: sysconfig.py-20091210
            # Assume the executable is in the build directory.  The
            # pyconfig.h file should be in the same directory.  Since
            # the build directory may not be the source directory, we
            # must use "srcdir" from the makefile to find the "Include"
            # directory.
            base = os.path.dirname(os.path.abspath(sys.executable))
            if plat_specific:
                return base
            else:
                incdir = os.path.join(get_config_var('srcdir'), 'Include')
                return os.path.normpath(incdir)
        return os.path.join(prefix, "include", "python" + get_python_version())
    elif os.name == "nt":
        return os.path.join(prefix, "include")
    elif os.name == "os2":
        return os.path.join(prefix, "Include")
    else:
        raise DistutilsPlatformError(
            "I don't know where Python installs its C header files "
            "on platform '%s'" % os.name) 
Example #19
Source File: env.py    From KL-Loss with Apache License 2.0 5 votes vote down vote up
def get_detectron_ops_lib():
    """Retrieve Detectron ops library."""
    # Candidate prefixes for detectron ops lib path
    prefixes = [_CMAKE_INSTALL_PREFIX, sys.prefix, sys.exec_prefix] + sys.path
    # Candidate subdirs for detectron ops lib
    subdirs = ['lib', 'torch/lib']
    # Try to find detectron ops lib
    for prefix in prefixes:
        for subdir in subdirs:
            ops_path = os.path.join(prefix, subdir, _DETECTRON_OPS_LIB)
            if os.path.exists(ops_path):
                print('Found Detectron ops lib: {}'.format(ops_path))
                return ops_path
    raise Exception('Detectron ops lib not found') 
Example #20
Source File: test_doctest.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_coverage(coverdir):
    trace = test_support.import_module('trace')
    tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,],
                         trace=0, count=1)
    tracer.run('reload(doctest); test_main()')
    r = tracer.results()
    print 'Writing coverage results...'
    r.write_results(show_missing=True, summary=True,
                    coverdir=coverdir) 
Example #21
Source File: pydoc.py    From BinderFilter with MIT License 5 votes vote down vote up
def getdocloc(self, object):
        """Return the location of module docs or None"""

        try:
            file = inspect.getabsfile(object)
        except TypeError:
            file = '(built-in)'

        docloc = os.environ.get("PYTHONDOCS",
                                "http://docs.python.org/library")
        basedir = os.path.join(sys.exec_prefix, "lib",
                               "python"+sys.version[0:3])
        if (isinstance(object, type(os)) and
            (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                 'marshal', 'posix', 'signal', 'sys',
                                 'thread', 'zipimport') or
             (file.startswith(basedir) and
              not file.startswith(os.path.join(basedir, 'site-packages')))) and
            object.__name__ not in ('xml.etree', 'test.pydoc_mod')):
            if docloc.startswith("http://"):
                docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
            else:
                docloc = os.path.join(docloc, object.__name__ + ".html")
        else:
            docloc = None
        return docloc

# -------------------------------------------- HTML documentation generator 
Example #22
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_mta():
    ipi = IronPythonInstance(executable, exec_prefix, '-X:MTA')
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("import System")
    response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)")
    AreEqual(response, "'MTA'")
    
    ipi.ExecutePartialLine("class C:pass")
    response = ipi.ExecuteLine("")
    AreEqual(response, "")
    
    response = ipi.ExecuteLine("str(System.Threading.Thread.CurrentThread.ApartmentState)")
    AreEqual(response, "'MTA'")
    ipi.End() 
Example #23
Source File: sysconfig.py    From Computable with MIT License 5 votes vote down vote up
def get_python_inc(plat_specific=0, prefix=None):
    """Return the directory containing installed Python header files.

    If 'plat_specific' is false (the default), this is the path to the
    non-platform-specific header files, i.e. Python.h and so on;
    otherwise, this is the path to platform-specific header files
    (namely pyconfig.h).

    If 'prefix' is supplied, use it instead of sys.prefix or
    sys.exec_prefix -- i.e., ignore 'plat_specific'.
    """
    if prefix is None:
        prefix = plat_specific and EXEC_PREFIX or PREFIX

    if os.name == "posix":
        if python_build:
            buildir = os.path.dirname(sys.executable)
            if plat_specific:
                # python.h is located in the buildir
                inc_dir = buildir
            else:
                # the source dir is relative to the buildir
                srcdir = os.path.abspath(os.path.join(buildir,
                                         get_config_var('srcdir')))
                # Include is located in the srcdir
                inc_dir = os.path.join(srcdir, "Include")
            return inc_dir
        return os.path.join(prefix, "include", "python" + get_python_version())
    elif os.name == "nt":
        return os.path.join(prefix, "include")
    elif os.name == "os2":
        return os.path.join(prefix, "Include")
    else:
        raise DistutilsPlatformError(
            "I don't know where Python installs its C header files "
            "on platform '%s'" % os.name) 
Example #24
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ipy_dash_c():
    """verify ipy -c cmd doesn't print expression statements"""
    ipi = IronPythonInstance(executable, exec_prefix, "-c True;False")
    res = ipi.StartAndRunToCompletion()
    AreEqual(res[0], True)  # should have started
    AreEqual(res[1], '')    # no std out
    AreEqual(res[2], '')    # no std err
    AreEqual(res[3], 0)     # should return 0

#############################################################################
# CP11924 - verify 'from __future__ import division' works 
Example #25
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ipy_dash_m_negative():        
    # builtin modules should not work
    for modname in [ "sys", "datetime" ]:
        ipi = IronPythonInstance(executable, exec_prefix,
                                 extraArgs + " -m " + modname)
        res, output, err, exit = ipi.StartAndRunToCompletion()
        AreEqual(exit, -1)

    # Modules within packages should not work
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -m testpkg1.mod1")
    res, output, err, exit = ipi.StartAndRunToCompletion()
    AreEqual(res, True) # run should have worked
    AreEqual(exit, 1)   # should have returned 0
    Assert("SyntaxError: invalid syntax" in err,
           "stderr is:" + str(err)) 
Example #26
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_startup_dir():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("print dir()")
    AreEqual(sorted(eval(response)), sorted(['__builtins__', '__doc__', '__name__'])) 
Example #27
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_ipy_dash_S():
    """ipy -S should still install Lib into sys.path"""
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " -S")
    AreEqual(ipi.Start(), True)
    response = ipi.ExecuteLine("import sys")
    response = ipi.ExecuteLine("print sys.path")
    Assert(response.find('Lib') != -1) 
Example #28
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_thrown_from_thread():
    inputScript = path_combine(testpath.temporary_dir, "throwingfromthread.py")
    write_to_file(inputScript, '''
def f(): raise AssertionError, 'hello'
import thread, time
thread.start_new_thread(f, tuple())
time.sleep(2)
''')
    
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs + " " + inputScript)
    (result, output, output2, exitCode) = ipi.StartAndRunToCompletion()
    AreEqual(exitCode, 0)
    Assert("AssertionError: hello" in output2)
    Assert("IronPython." not in output2)     # '.' is necessary here
    ipi.End() 
Example #29
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_global_values():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecuteLine("import clr")
    response = ipi.ExecuteLine("[x for x in globals().values()]")
    Assert(response.startswith('['))
    d = eval(ipi.ExecuteLine("globals().fromkeys(['a', 'b'], 'c')"))
    AreEqual(d, {'a':'c', 'b':'c'}) 
Example #30
Source File: test_interactive.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def test_indentation_interactive():
    ipi = IronPythonInstance(executable, exec_prefix, extraArgs)
    AreEqual(ipi.Start(), True)
    ipi.ExecutePartialLine("class C:pass")
    response = ipi.ExecuteLine("")
    AreEqual(response, "")
    ipi.ExecutePartialLine("class D(C):")
    response = ipi.ExecuteLine("", True)
    Assert("IndentationError:" in response)
    ipi.End()

###########################################################
# test /mta w/ no other args