Python os.chdir() Examples

The following are code examples for showing how to use os.chdir(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: leapp-repository   Author: oamg   File: conftest.py    Apache License 2.0 6 votes vote down vote up
def pytest_sessionstart(session):

    actor_path = os.environ.get('LEAPP_TESTED_ACTOR', None)
    library_path = os.environ.get('LEAPP_TESTED_LIBRARY', None)

    if actor_path:
        repo = load_repo(actor_path)

        actor = None
        # find which actor is being tested
        for a in repo.actors:
            if a.full_path == actor_path.rstrip('/'):
                actor = a
                break

        if not actor:
            return

        # load actor context so libraries can be imported on module level
        session.leapp_repository = repo
        session.actor_context = actor.injected_context()
        session.actor_context.__enter__()
    elif library_path:
        load_repo(library_path)
        os.chdir(library_path) 
Example 2
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = make_tarball(base_name, 'dist', compress=None,
                                        owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example 3
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_record(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(py_modules=['hello'],
                                             scripts=['sayhi'])
        os.chdir(project_dir)
        self.write_file('hello.py', "def main(): print 'o hai'")
        self.write_file('sayhi', 'from hello import main; main()')

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = ['hello.py', 'hello.pyc', 'sayhi',
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 4
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_deep_recursion(self):
            depth = 10
            old_path = abspath('.')
            try:
                os.mkdir(ABSTFN)
                for i in range(depth):
                    os.symlink('/'.join(['%d' % i] * 10), ABSTFN + '/%d' % (i + 1))
                os.symlink('.', ABSTFN + '/0')
                self.assertEqual(realpath(ABSTFN + '/%d' % depth), ABSTFN)

                # Test using relative path as well.
                os.chdir(ABSTFN)
                self.assertEqual(realpath('%d' % depth), ABSTFN)
            finally:
                os.chdir(old_path)
                for i in range(depth + 1):
                    test_support.unlink(ABSTFN + '/%d' % i)
                safe_rmdir(ABSTFN) 
Example 5
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_resolve_parents(self):
            # We also need to resolve any symlinks in the parents of a relative
            # path passed to realpath. E.g.: current working directory is
            # /usr/doc with 'doc' being a symlink to /usr/share/doc. We call
            # realpath("a"). This should return /usr/share/doc/a/.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/y")
                os.symlink(ABSTFN + "/y", ABSTFN + "/k")

                os.chdir(ABSTFN + "/k")
                self.assertEqual(realpath("a"), ABSTFN + "/y/a")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "/k")
                safe_rmdir(ABSTFN + "/y")
                safe_rmdir(ABSTFN) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_realpath_resolve_first(self):
            # Bug #1213894: The first component of the path, if not absolute,
            # must be resolved too.

            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.symlink(ABSTFN, ABSTFN + "link")
                os.chdir(dirname(ABSTFN))

                base = basename(ABSTFN)
                self.assertEqual(realpath(base + "link"), ABSTFN)
                self.assertEqual(realpath(base + "link/k"), ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "link")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_cwd(self):
        tmpdir = tempfile.gettempdir()
        # We cannot use os.path.realpath to canonicalize the path,
        # since it doesn't expand Tru64 {memb} strings. See bug 1063571.
        cwd = os.getcwd()
        os.chdir(tmpdir)
        tmpdir = os.getcwd()
        os.chdir(cwd)
        p = subprocess.Popen([sys.executable, "-c",
                          'import sys,os;'
                          'sys.stdout.write(os.getcwd())'],
                         stdout=subprocess.PIPE,
                         cwd=tmpdir)
        self.addCleanup(p.stdout.close)
        normcase = os.path.normcase
        self.assertEqual(normcase(p.stdout.read()), normcase(tmpdir)) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_tarfile_root_owner(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        group = grp.getgrgid(0)[0]
        owner = pwd.getpwuid(0)[0]
        try:
            archive_name = _make_tarball(base_name, 'dist', compress=None,
                                         owner=owner, group=group)
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        self.assertTrue(os.path.exists(archive_name))

        # now checks the rights
        archive = tarfile.open(archive_name)
        try:
            for member in archive.getmembers():
                self.assertEqual(member.uid, 0)
                self.assertEqual(member.gid, 0)
        finally:
            archive.close() 
Example 9
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_normalize(self):
        files = set(f for f in self.files if isinstance(f, unicode))
        others = set()
        for nf in set(['NFC', 'NFD', 'NFKC', 'NFKD']):
            others |= set(normalize(nf, file) for file in files)
        others -= files
        for name in others:
            self._apply_failure(open, name, IOError)
            self._apply_failure(os.stat, name, OSError)
            self._apply_failure(os.chdir, name, OSError)
            self._apply_failure(os.rmdir, name, OSError)
            self._apply_failure(os.remove, name, OSError)
            # listdir may append a wildcard to the filename, so dont check
            self._apply_failure(os.listdir, name, OSError, False)

    # Skip the test on darwin, because darwin uses a normalization different
    # than Python NFD normalization: filenames are different even if we use
    # Python NFD normalization. 
Example 10
Project: ieml   Author: IEMLdev   File: word_to_latex.py    GNU General Public License v3.0 6 votes vote down vote up
def compile_latex(latex_str):
    old_cwd = os.getcwd()

    with tempfile.TemporaryDirectory() as tempdir:
        path = os.path.join(tempdir, 'output')

        logger.error(path)
        doc = Document(path, data=[dumps_list([latex_str], escape=False)], geometry_options='landscape')

        doc.packages.append(Package('xcolor', ['dvipsnames','table']))
        try:
            doc.generate_pdf(clean_tex=False, silent=False)
            doc.generate_tex()
        except subprocess.CalledProcessError as e:
            os.chdir(old_cwd)  # because pylatex change it but doesnt restore it
            raise e

        with open(path + '.pdf', 'rb') as fp:
            return fp.read() 
Example 11
Project: pydockenv   Author: se7entyse7en   File: test_port_mapper.py    Apache License 2.0 6 votes vote down vote up
def test_port_mapping_single_port(self):
        env_name = self._env_name()
        proj_name, py_version = 'test-proj', '3.7'

        proj_dir = self._create_project_dir(proj_name)
        self._commander.run(
            f'create --name={env_name} --version={py_version} {str(proj_dir)}')
        with self._commander.active_env(env_name) as env:
            os.chdir(proj_dir)

            port = 8000
            out = self._commander.run(
                f'run -d -p {port} -- python -m http.server {port}', env=env)
            self.assertCommandOk(out)
            self.assertPortMapperExists(env_name, port)

            s = requests.Session()
            s.mount('http://', HTTPAdapter(
                max_retries=Retry(connect=3, backoff_factor=1)))
            r = s.get(f'http://localhost:{port}')

            self.assertEqual(r.status_code, 200, msg=r.content) 
Example 12
Project: pydockenv   Author: se7entyse7en   File: test_port_mapper.py    Apache License 2.0 6 votes vote down vote up
def test_port_mapping_multi_ports(self):
        env_name = self._env_name()
        proj_name, py_version = 'test-proj', '3.7'

        proj_dir = self._create_project_dir(proj_name)
        self._commander.run(
            f'create --name={env_name} --version={py_version} {str(proj_dir)}')
        with self._commander.active_env(env_name) as env:
            os.chdir(proj_dir)

            for port in range(8000, 8003):
                out = self._commander.run(
                    f'run -d -p {port} -- python -m http.server {port}',
                    env=env
                )
                self.assertCommandOk(out)
                self.assertPortMapperExists(env_name, port)

                s = requests.Session()
                s.mount('http://', HTTPAdapter(
                    max_retries=Retry(connect=3, backoff_factor=1)))
                r = s.get(f'http://localhost:{port}')

                self.assertEqual(r.status_code, 200, msg=r.content) 
Example 13
Project: pydockenv   Author: se7entyse7en   File: base.py    Apache License 2.0 6 votes vote down vote up
def tearDown(self):
        os.chdir(self._cwd)
        try:
            for i in range(1, self._env_index):
                env_name = self._create_env_name(i)
                try:
                    Client.get_instance().containers.get(
                        definitions.CONTAINERS_PREFIX + env_name).remove(
                            force=True)
                    delete_network(env_name)
                except docker.errors.NotFound:
                    pass

                self._remove_port_mappers(env_name)
        finally:
            shutil.rmtree(self._test_dir.name) 
Example 14
Project: 2015-SpaceInvaders-Bot-Python   Author: EntelectChallenge   File: ez_setup.py    MIT License 6 votes vote down vote up
def archive_context(filename):
    """
    Unzip filename to a temporary directory, set to the cwd.

    The unzipped target is cleaned up after.
    """
    tmpdir = tempfile.mkdtemp()
    log.warn('Extracting in %s', tmpdir)
    old_wd = os.getcwd()
    try:
        os.chdir(tmpdir)
        with ContextualZipFile(filename) as archive:
            archive.extractall()

        # going in the directory
        subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
        os.chdir(subdir)
        log.warn('Now working in %s', subdir)
        yield

    finally:
        os.chdir(old_wd)
        shutil.rmtree(tmpdir) 
Example 15
Project: ubittool   Author: carlosperate   File: make.py    MIT License 5 votes vote down vote up
def _set_cwd():
    """Set cwd to the path necessary for these commands to work correctly.

    All commands depend on this file folder being the current working
    directory.
    """
    os.chdir(_this_file_dir()) 
Example 16
Project: pyblish-win   Author: pyblish   File: setuptools_build_ext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def write_stub(self, output_dir, ext, compile=False):
        log.info("writing stub loader for %s to %s",ext._full_name, output_dir)
        stub_file = os.path.join(output_dir, *ext._full_name.split('.'))+'.py'
        if compile and os.path.exists(stub_file):
            raise DistutilsError(stub_file+" already exists! Please delete.")
        if not self.dry_run:
            f = open(stub_file,'w')
            f.write('\n'.join([
                "def __bootstrap__():",
                "   global __bootstrap__, __file__, __loader__",
                "   import sys, os, pkg_resources, imp"+if_dl(", dl"),
                "   __file__ = pkg_resources.resource_filename(__name__,%r)"
                   % os.path.basename(ext._file_name),
                "   del __bootstrap__",
                "   if '__loader__' in globals():",
                "       del __loader__",
                if_dl("   old_flags = sys.getdlopenflags()"),
                "   old_dir = os.getcwd()",
                "   try:",
                "     os.chdir(os.path.dirname(__file__))",
                if_dl("     sys.setdlopenflags(dl.RTLD_NOW)"),
                "     imp.load_dynamic(__name__,__file__)",
                "   finally:",
                if_dl("     sys.setdlopenflags(old_flags)"),
                "     os.chdir(old_dir)",
                "__bootstrap__()",
                "" # terminal \n
            ]))
            f.close()
        if compile:
            from distutils.util import byte_compile
            byte_compile([stub_file], optimize=0,
                         force=True, dry_run=self.dry_run)
            optimize = self.get_finalized_command('install_lib').optimize
            if optimize > 0:
                byte_compile([stub_file], optimize=optimize,
                             force=True, dry_run=self.dry_run)
            if os.path.exists(stub_file) and not self.dry_run:
                os.unlink(stub_file) 
Example 17
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        # PyPIRCCommandTestCase creates a temp dir already
        # and put it in self.tmp_dir
        super(SDistTestCase, self).setUp()
        # setting up an environment
        self.old_path = os.getcwd()
        os.mkdir(join(self.tmp_dir, 'somecode'))
        os.mkdir(join(self.tmp_dir, 'dist'))
        # a package, and a README
        self.write_file((self.tmp_dir, 'README'), 'xxx')
        self.write_file((self.tmp_dir, 'somecode', '__init__.py'), '#')
        self.write_file((self.tmp_dir, 'setup.py'), SETUP_PY)
        os.chdir(self.tmp_dir) 
Example 18
Project: pyblish-win   Author: pyblish   File: test_sdist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # back to normal
        os.chdir(self.old_path)
        super(SDistTestCase, self).tearDown() 
Example 19
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _make_tarball(self, target_name):
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')
        os.mkdir(os.path.join(tmpdir, 'sub'))
        self.write_file([tmpdir, 'sub', 'file3'], 'xxx')

        tmpdir2 = self.mkdtemp()
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "source and target should be on same drive")

        base_name = os.path.join(tmpdir2, target_name)

        # working with relative paths to avoid tar warnings
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], '.')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, target_name)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(splitdrive(base_name)[1], '.', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
        self.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1) 
Example 21
Project: pyblish-win   Author: pyblish   File: support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        # Restore working dir, for Solaris and derivatives, where rmdir()
        # on the current directory fails.
        os.chdir(self.old_cwd)
        super(TempdirManager, self).tearDown()
        while self.tempdirs:
            d = self.tempdirs.pop()
            shutil.rmtree(d, os.name in ('nt', 'cygwin')) 
Example 22
Project: pyblish-win   Author: pyblish   File: test_build_py.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_empty_package_dir(self):
        # See SF 1668596/1720897.
        cwd = os.getcwd()

        # create the distribution files.
        sources = self.mkdtemp()
        open(os.path.join(sources, "__init__.py"), "w").close()

        testdir = os.path.join(sources, "doc")
        os.mkdir(testdir)
        open(os.path.join(testdir, "testfile"), "w").close()

        os.chdir(sources)
        old_stdout = sys.stdout
        sys.stdout = StringIO.StringIO()

        try:
            dist = Distribution({"packages": ["pkg"],
                                 "package_dir": {"pkg": ""},
                                 "package_data": {"pkg": ["doc/*"]}})
            # script_name need not exist, it just need to be initialized
            dist.script_name = os.path.join(sources, "setup.py")
            dist.script_args = ["build"]
            dist.parse_command_line()

            try:
                dist.run_commands()
            except DistutilsFileError:
                self.fail("failed package_data test when package_dir is ''")
        finally:
            # Restore state.
            os.chdir(cwd)
            sys.stdout = old_stdout 
Example 23
Project: pyblish-win   Author: pyblish   File: test_build_py.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_dir_in_package_data(self):
        """
        A directory in package_data should not be added to the filelist.
        """
        # See bug 19286
        sources = self.mkdtemp()
        pkg_dir = os.path.join(sources, "pkg")

        os.mkdir(pkg_dir)
        open(os.path.join(pkg_dir, "__init__.py"), "w").close()

        docdir = os.path.join(pkg_dir, "doc")
        os.mkdir(docdir)
        open(os.path.join(docdir, "testfile"), "w").close()

        # create the directory that could be incorrectly detected as a file
        os.mkdir(os.path.join(docdir, 'otherdir'))

        os.chdir(sources)
        dist = Distribution({"packages": ["pkg"],
                             "package_data": {"pkg": ["doc/*"]}})
        # script_name need not exist, it just need to be initialized
        dist.script_name = os.path.join(sources, "setup.py")
        dist.script_args = ["build"]
        dist.parse_command_line()

        try:
            dist.run_commands()
        except DistutilsFileError:
            self.fail("failed package_data when data dir includes a dir") 
Example 24
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        os.chdir(self.old_location)
        sys.argv = self.old_sys_argv[0]
        sys.argv[:] = self.old_sys_argv[1]
        super(BuildRpmTestCase, self).tearDown()

    # XXX I am unable yet to make this test work without
    # spurious sdtout/stderr output under Mac OS X 
Example 25
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_quiet(self):
        # let's create a package
        tmp_dir = self.mkdtemp()
        os.environ['HOME'] = tmp_dir   # to confine dir '.rpmdb' creation
        pkg_dir = os.path.join(tmp_dir, 'foo')
        os.mkdir(pkg_dir)
        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
        self.write_file((pkg_dir, 'foo.py'), '#')
        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
        self.write_file((pkg_dir, 'README'), '')

        dist = Distribution({'name': 'foo', 'version': '0.1',
                             'py_modules': ['foo'],
                             'url': 'xxx', 'author': 'xxx',
                             'author_email': 'xxx'})
        dist.script_name = 'setup.py'
        os.chdir(pkg_dir)

        sys.argv = ['setup.py']
        cmd = bdist_rpm(dist)
        cmd.fix_python = True

        # running in quiet mode
        cmd.quiet = 1
        cmd.ensure_finalized()
        cmd.run()

        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
        self.assertIn('foo-0.1-1.noarch.rpm', dist_created)

        # bug #2945: upload ignores bdist_rpm files
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)

    # XXX I am unable yet to make this test work without
    # spurious sdtout/stderr output under Mac OS X 
Example 26
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_no_optimize_flag(self):
        # let's create a package that brakes bdist_rpm
        tmp_dir = self.mkdtemp()
        os.environ['HOME'] = tmp_dir   # to confine dir '.rpmdb' creation
        pkg_dir = os.path.join(tmp_dir, 'foo')
        os.mkdir(pkg_dir)
        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
        self.write_file((pkg_dir, 'foo.py'), '#')
        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
        self.write_file((pkg_dir, 'README'), '')

        dist = Distribution({'name': 'foo', 'version': '0.1',
                             'py_modules': ['foo'],
                             'url': 'xxx', 'author': 'xxx',
                             'author_email': 'xxx'})
        dist.script_name = 'setup.py'
        os.chdir(pkg_dir)

        sys.argv = ['setup.py']
        cmd = bdist_rpm(dist)
        cmd.fix_python = True

        cmd.quiet = 1
        cmd.ensure_finalized()
        cmd.run()

        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
        self.assertIn('foo-0.1-1.noarch.rpm', dist_created)

        # bug #2945: upload ignores bdist_rpm files
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.src.rpm'), dist.dist_files)
        self.assertIn(('bdist_rpm', 'any', 'dist/foo-0.1-1.noarch.rpm'), dist.dist_files)

        os.remove(os.path.join(pkg_dir, 'dist', 'foo-0.1-1.noarch.rpm')) 
Example 27
Project: pyblish-win   Author: pyblish   File: test_bdist_dumb.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_finalize_options(self):
        pkg_dir, dist = self.create_dist()
        os.chdir(pkg_dir)
        cmd = bdist_dumb(dist)
        self.assertEqual(cmd.bdist_dir, None)
        cmd.finalize_options()

        # bdist_dir is initialized to bdist_base/dumb if not set
        base = cmd.get_finalized_command('bdist').bdist_base
        self.assertEqual(cmd.bdist_dir, os.path.join(base, 'dumb'))

        # the format is set to a default value depending on the os.name
        default = cmd.default_format[os.name]
        self.assertEqual(cmd.format, default) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_install.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_record_extensions(self):
        install_dir = self.mkdtemp()
        project_dir, dist = self.create_dist(ext_modules=[
            Extension('xx', ['xxmodule.c'])])
        os.chdir(project_dir)
        support.copy_xxmodule_c(project_dir)

        buildextcmd = build_ext(dist)
        support.fixup_build_ext(buildextcmd)
        buildextcmd.ensure_finalized()

        cmd = install(dist)
        dist.command_obj['install'] = cmd
        dist.command_obj['build_ext'] = buildextcmd
        cmd.root = install_dir
        cmd.record = os.path.join(project_dir, 'filelist')
        cmd.ensure_finalized()
        cmd.run()

        f = open(cmd.record)
        try:
            content = f.read()
        finally:
            f.close()

        found = [os.path.basename(line) for line in content.splitlines()]
        expected = [_make_ext_name('xx'),
                    'UNKNOWN-0.0.0-py%s.%s.egg-info' % sys.version_info[:2]]
        self.assertEqual(found, expected) 
Example 29
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def restore_cwd(self, saved_cwd):
        os.chdir(saved_cwd) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_realpath_symlink_loops(self):
            # Bug #930024, return the path unchanged if we get into an infinite
            # symlink loop.
            try:
                old_path = abspath('.')
                os.symlink(ABSTFN, ABSTFN)
                self.assertEqual(realpath(ABSTFN), ABSTFN)

                os.symlink(ABSTFN+"1", ABSTFN+"2")
                os.symlink(ABSTFN+"2", ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"1"), ABSTFN+"1")
                self.assertEqual(realpath(ABSTFN+"2"), ABSTFN+"2")

                self.assertEqual(realpath(ABSTFN+"1/x"), ABSTFN+"1/x")
                self.assertEqual(realpath(ABSTFN+"1/.."), dirname(ABSTFN))
                self.assertEqual(realpath(ABSTFN+"1/../x"), dirname(ABSTFN) + "/x")
                os.symlink(ABSTFN+"x", ABSTFN+"y")
                self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "y"),
                                ABSTFN + "y")
                self.assertEqual(realpath(ABSTFN+"1/../" + basename(ABSTFN) + "1"),
                                ABSTFN + "1")

                os.symlink(basename(ABSTFN) + "a/b", ABSTFN+"a")
                self.assertEqual(realpath(ABSTFN+"a"), ABSTFN+"a/b")

                os.symlink("../" + basename(dirname(ABSTFN)) + "/" +
                        basename(ABSTFN) + "c", ABSTFN+"c")
                self.assertEqual(realpath(ABSTFN+"c"), ABSTFN+"c")

                # Test using relative path as well.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN)), ABSTFN)
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN)
                test_support.unlink(ABSTFN+"1")
                test_support.unlink(ABSTFN+"2")
                test_support.unlink(ABSTFN+"y")
                test_support.unlink(ABSTFN+"c")
                test_support.unlink(ABSTFN+"a") 
Example 31
Project: pyblish-win   Author: pyblish   File: test_posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_realpath_resolve_before_normalizing(self):
            # Bug #990669: Symbolic links should be resolved before we
            # normalize the path. E.g.: if we have directories 'a', 'k' and 'y'
            # in the following hierarchy:
            # a/k/y
            #
            # and a symbolic link 'link-y' pointing to 'y' in directory 'a',
            # then realpath("link-y/..") should return 'k', not 'a'.
            try:
                old_path = abspath('.')
                os.mkdir(ABSTFN)
                os.mkdir(ABSTFN + "/k")
                os.mkdir(ABSTFN + "/k/y")
                os.symlink(ABSTFN + "/k/y", ABSTFN + "/link-y")

                # Absolute path.
                self.assertEqual(realpath(ABSTFN + "/link-y/.."), ABSTFN + "/k")
                # Relative path.
                os.chdir(dirname(ABSTFN))
                self.assertEqual(realpath(basename(ABSTFN) + "/link-y/.."),
                                 ABSTFN + "/k")
            finally:
                os.chdir(old_path)
                test_support.unlink(ABSTFN + "/link-y")
                safe_rmdir(ABSTFN + "/k/y")
                safe_rmdir(ABSTFN + "/k")
                safe_rmdir(ABSTFN) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        try:
            os.chdir(self.cwd)
            try:
                shutil.rmtree(self.tempdir)
            except OSError:
                pass
        finally:
            BaseTestCase.tearDown(self) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        BaseTestCase.setUp(self)
        self.parent_dir = tempfile.mkdtemp()
        self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
        self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
        os.mkdir(self.cgi_dir)
        os.mkdir(self.cgi_child_dir)

        # The shebang line should be pure ASCII: use symlink if possible.
        # See issue #7668.
        if hasattr(os, 'symlink'):
            self.pythonexe = os.path.join(self.parent_dir, 'python')
            os.symlink(sys.executable, self.pythonexe)
        else:
            self.pythonexe = sys.executable

        self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
        with open(self.nocgi_path, 'w') as fp:
            fp.write(cgi_file1 % self.pythonexe)
        os.chmod(self.nocgi_path, 0777)

        self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
        with open(self.file1_path, 'w') as file1:
            file1.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file1_path, 0777)

        self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
        with open(self.file2_path, 'w') as file2:
            file2.write(cgi_file2 % self.pythonexe)
        os.chmod(self.file2_path, 0777)

        self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
        with open(self.file3_path, 'w') as file3:
            file3.write(cgi_file1 % self.pythonexe)
        os.chmod(self.file3_path, 0777)

        self.cwd = os.getcwd()
        os.chdir(self.parent_dir) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def tearDown(self):
        try:
            os.chdir(self.cwd)
            if self.pythonexe != sys.executable:
                os.remove(self.pythonexe)
            os.remove(self.nocgi_path)
            os.remove(self.file1_path)
            os.remove(self.file2_path)
            os.remove(self.file3_path)
            os.rmdir(self.cgi_child_dir)
            os.rmdir(self.cgi_dir)
            os.rmdir(self.parent_dir)
        finally:
            BaseTestCase.tearDown(self) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_main(verbose=None):
    try:
        cwd = os.getcwd()
        test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
                                  SimpleHTTPRequestHandlerTestCase,
                                  BaseHTTPServerTestCase,
                                  SimpleHTTPServerTestCase,
                                  CGIHTTPServerTestCase
                                 )
    finally:
        os.chdir(cwd) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_add_self(self):
        # Test for #1257255.
        dstname = os.path.abspath(tmpname)

        tar = tarfile.open(tmpname, self.mode)
        self.assertTrue(tar.name == dstname, "archive name must be absolute")

        tar.add(dstname)
        self.assertTrue(tar.getnames() == [], "added the archive to itself")

        cwd = os.getcwd()
        os.chdir(TEMPDIR)
        tar.add(dstname)
        os.chdir(cwd)
        self.assertTrue(tar.getnames() == [], "added the archive to itself") 
Example 37
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_exceptions(self):
        # caught & re-raised exceptions
        with self.assertRaises(OSError) as c:
            p = subprocess.Popen([sys.executable, "-c", ""],
                                 cwd="/this/path/does/not/exist")
        # The attribute child_traceback should contain "os.chdir" somewhere.
        self.assertIn("os.chdir", c.exception.child_traceback) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_make_tarball(self):
        # creating something to tar
        tmpdir = self.mkdtemp()
        self.write_file([tmpdir, 'file1'], 'xxx')
        self.write_file([tmpdir, 'file2'], 'xxx')
        os.mkdir(os.path.join(tmpdir, 'sub'))
        self.write_file([tmpdir, 'sub', 'file3'], 'xxx')

        tmpdir2 = self.mkdtemp()
        # force shutil to create the directory
        os.rmdir(tmpdir2)
        unittest.skipUnless(splitdrive(tmpdir)[0] == splitdrive(tmpdir2)[0],
                            "source and target should be on same drive")

        base_name = os.path.join(tmpdir2, 'archive')

        # working with relative paths to avoid tar warnings
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(splitdrive(base_name)[1], '.')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(splitdrive(base_name)[1], '.', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_make_zipfile_in_curdir(self):
        # Issue #21280
        root_dir = self.mkdtemp()
        saved_dir = os.getcwd()
        try:
            os.chdir(root_dir)
            self.assertEqual(make_archive('test', 'zip'), 'test.zip')
            self.assertTrue(os.path.isfile('test.zip'))
        finally:
            os.chdir(saved_dir) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_chdir(self):
        self.assertRaises(WindowsError, os.chdir, test_support.TESTFN) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_chdir(self):
        posix.chdir(os.curdir)
        self.assertRaises(OSError, posix.chdir, test_support.TESTFN) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_py_compile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.directory = tempfile.mkdtemp()
        self.source_path = os.path.join(self.directory, '_test.py')
        self.pyc_path = self.source_path + 'c'
        self.cwd_drive = os.path.splitdrive(os.getcwd())[0]
        # In these tests we compute relative paths.  When using Windows, the
        # current working directory path and the 'self.source_path' might be
        # on different drives.  Therefore we need to switch to the drive where
        # the temporary source file lives.
        drive = os.path.splitdrive(self.source_path)[0]
        if drive:
            os.chdir(drive)

        with open(self.source_path, 'w') as file:
            file.write('x = 123\n') 
Example 43
Project: pyblish-win   Author: pyblish   File: test_py_compile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cwd(self):
        cwd = os.getcwd()
        os.chdir(self.directory)
        py_compile.compile(os.path.basename(self.source_path),
                           os.path.basename(self.pyc_path))
        os.chdir(cwd)
        self.assertTrue(os.path.exists(self.pyc_path)) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_failures(self):
        # Pass non-existing Unicode filenames all over the place.
        for name in self.files:
            name = "not_" + name
            self._apply_failure(open, name, IOError)
            self._apply_failure(os.stat, name, OSError)
            self._apply_failure(os.chdir, name, OSError)
            self._apply_failure(os.rmdir, name, OSError)
            self._apply_failure(os.remove, name, OSError)
            # listdir may append a wildcard to the filename, so dont check
            self._apply_failure(os.listdir, name, OSError, False) 
Example 45
Project: pyblish-win   Author: pyblish   File: test_pep277.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directory(self):
        dirname = os.path.join(test_support.TESTFN,
                               u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
        filename = u'\xdf-\u66e8\u66e9\u66eb'
        oldwd = os.getcwd()
        os.mkdir(dirname)
        os.chdir(dirname)
        try:
            with open(filename, 'w') as f:
                f.write((filename + '\n').encode("utf-8"))
            os.access(filename,os.R_OK)
            os.remove(filename)
        finally:
            os.chdir(oldwd)
            os.rmdir(dirname) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.temp_dir = tempfile.mkdtemp()
        self.old_dir = os.getcwd()
        os.chdir(self.temp_dir) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_unicode_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_directory(self, make_name, chdir_name, encoded):
        cwd = os.getcwd()
        if os.path.isdir(make_name):
            os.rmdir(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                if not encoded:
                    cwd_result = os.getcwdu()
                    name_result = make_name
                else:
                    cwd_result = os.getcwd().decode(TESTFN_ENCODING)
                    name_result = make_name.decode(TESTFN_ENCODING)

                cwd_result = unicodedata.normalize("NFD", cwd_result)
                name_result = unicodedata.normalize("NFD", name_result)

                self.assertEqual(os.path.basename(cwd_result),name_result)
            finally:
                os.chdir(cwd)
        finally:
            os.rmdir(make_name)

    # The '_test' functions 'entry points with params' - ie, what the
    # top-level 'test' functions would be if they could take params 
Example 48
Project: pyblish-win   Author: pyblish   File: test_unicode_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_directories(self):
        # For all 'equivalent' combinations:
        #  Make dir with encoded, chdir with unicode, checkdir with encoded
        #  (or unicode/encoded/unicode, etc
        ext = ".dir"
        self._do_directory(TESTFN_ENCODED+ext, TESTFN_ENCODED+ext, True)
        self._do_directory(TESTFN_ENCODED+ext, TESTFN_UNICODE+ext, True)
        self._do_directory(TESTFN_UNICODE+ext, TESTFN_ENCODED+ext, False)
        self._do_directory(TESTFN_UNICODE+ext, TESTFN_UNICODE+ext, False)
        # Our directory name that can't use a non-unicode name.
        if TESTFN_UNENCODABLE is not None:
            self._do_directory(TESTFN_UNENCODABLE+ext,
                               TESTFN_UNENCODABLE+ext,
                               False) 
Example 49
Project: pyblish-win   Author: pyblish   File: ScriptBinding.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_module_event(self, event):
        """Run the module after setting up the environment.

        First check the syntax.  If OK, make sure the shell is active and
        then transfer the arguments, set the run environment's working
        directory to the directory of the module being executed and also
        add that directory to its sys.path if not already included.

        """
        filename = self.getfilename()
        if not filename:
            return 'break'
        code = self.checksyntax(filename)
        if not code:
            return 'break'
        if not self.tabnanny(filename):
            return 'break'
        interp = self.shell.interp
        if PyShell.use_subprocess:
            interp.restart_subprocess(with_cwd=False)
        dirname = os.path.dirname(filename)
        # XXX Too often this discards arguments the user just set...
        interp.runcommand("""if 1:
            __file__ = {filename!r}
            import sys as _sys
            from os.path import basename as _basename
            if (not _sys.argv or
                _basename(_sys.argv[0]) != _basename(__file__)):
                _sys.argv = [__file__]
            import os as _os
            _os.chdir({dirname!r})
            del _sys, _basename, _os
            \n""".format(filename=filename, dirname=dirname))
        interp.prepend_syspath(filename)
        # XXX KBK 03Jul04 When run w/o subprocess, runtime warnings still
        #         go to __stderr__.  With subprocess, they go to the shell.
        #         Need to change streams in PyShell.ModifiedInterpreter.
        interp.runcode(code)
        return 'break' 
Example 50
Project: arm_now   Author: nongiach   File: arm_now.py    MIT License 5 votes vote down vote up
def do_offline():
    URL = "https://github.com/nongiach/arm_now_templates/archive/master.zip"
    templates = str(Path.home()) + "/.config/arm_now/templates/"
    master_zip = str(Path.home()) + "/.config/arm_now/templates/master.zip"
    os.makedirs(templates)
    # download_from_github(arch)
    download(URL, master_zip, Config.DOWNLOAD_CACHE_DIR)
    os.chdir(templates)
    check_call("unzip master.zip", shell=True)
    check_call("mv arm_now_templates-master/* .", shell=True)
    check_call("rm -rf arm_now_templates-master/ README.md master.zip", shell=True) 
Example 51
Project: Mzo-Cli   Author: jamesstidard   File: deploy-homebrew.py    MIT License 5 votes vote down vote up
def change_dir(dir_):
    cwd = os.getcwd()
    os.chdir(dir_)
    yield
    os.chdir(cwd) 
Example 52
Project: Mzo-Cli   Author: jamesstidard   File: deploy-snapcraft.py    MIT License 5 votes vote down vote up
def change_dir(dir_):
    cwd = os.getcwd()
    os.chdir(dir_)
    yield
    os.chdir(cwd) 
Example 53
Project: pydockenv   Author: se7entyse7en   File: test_others.py    Apache License 2.0 5 votes vote down vote up
def test_run(self):
        data = [
            {
                'env_name': self._env_name(),
                'proj_name': 'test-proj-1',
                'v': '3.7',
            },
            {
                'env_name': self._env_name(),
                'proj_name': 'test-proj-2',
                'v': '3.6',
            },
            {
                'env_name': self._env_name(),
                'proj_name': 'test-proj-3',
                'v': '2.7',
            },
        ]

        for d in data:
            proj_dir = self._create_project_dir(d['proj_name'])
            out = self._commander.run(
                f"create --name={d['env_name']} --version={d['v']} "
                f"{str(proj_dir)}"
            )
            self.assertCommandOk(out)
            with self._commander.active_env(d['env_name']) as env:
                os.chdir(proj_dir)
                out = self._commander.run('run -- python --version', env=env)
                self.assertCommandOk(out)
                self.assertIn(f"Python {d['v']}", out.stdout.decode('utf8'))

            os.chdir(definitions.ROOT_DIR) 
Example 54
Project: pydockenv   Author: se7entyse7en   File: test_dependency.py    Apache License 2.0 5 votes vote down vote up
def test_deps_handling(self):
        env_name = self._env_name()
        proj_name, py_version = 'test-proj', '3.7'

        proj_dir = self._create_project_dir(proj_name)
        out = self._commander.run(
            f'create --name={env_name} --version={py_version} {str(proj_dir)}')
        self.assertCommandOk(out)

        with self._commander.active_env(env_name) as env:
            os.chdir(proj_dir)

            out = self._commander.run('list-packages', env=env)
            self.assertCommandOk(out)
            self.assertNotIn(f'pydockenv', out.stdout.decode('utf8'))

            out = self._commander.run('install pydockenv', env=env)
            self.assertCommandOk(out)

            out = self._commander.run('list-packages', env=env)
            self.assertCommandOk(out)
            self.assertIn(f'pydockenv', out.stdout.decode('utf8'))

            out = self._commander.run('uninstall -y pydockenv ', env=env)
            self.assertCommandOk(out)

            out = self._commander.run('list-packages', env=env)
            self.assertCommandOk(out)
            self.assertNotIn(f'pydockenv', out.stdout.decode('utf8')) 
Example 55
Project: fortran_input_reader   Author: miroi   File: config.py    MIT License 5 votes vote down vote up
def run_cmake(command, build_path, default_build_path):
    """
    Execute CMake command.
    """
    topdir = os.getcwd()
    os.chdir(build_path)
    p = subprocess.Popen(command,
                         shell=True,
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout_coded, stderr_coded = p.communicate()
    stdout = stdout_coded.decode('UTF-8')
    stderr = stderr_coded.decode('UTF-8')
    if stderr:
        sys.stderr.write(stderr)
        sys.exit(1)
    # print cmake output to screen
    print(stdout)
    # write cmake output to file
    f = open('cmake_output', 'w')
    f.write(stdout)
    f.close()
    # change directory and return
    os.chdir(topdir)
    if 'Configuring incomplete' in stdout:
        # configuration was not successful
        if (build_path == default_build_path):
            # remove build_path iff not set by the user
            # otherwise removal can be dangerous
            shutil.rmtree(default_build_path)
    else:
        # configuration was successful
        save_setup_command(sys.argv, build_path)
        print_build_help(build_path, default_build_path) 
Example 56
Project: crawler   Author: fst034356   File: spider_meizitu.py    MIT License 5 votes vote down vote up
def mkdir(self, path):
        path = path.strip()
        isExixts = os.path.exists(os.path.join(cwd_path, path))
        if not isExixts:
            print(u'新建文件夹:{0}'.format(path))
            os.mkdir(os.path.join(cwd_path, path))
            os.chdir(os.path.join(cwd_path, path))
            return True
        else:
            print(u'文件夹已经存在了:{0}'.format(path))
            os.chdir(os.path.join(cwd_path, path))
            return False 
Example 57
Project: VisualNN   Author: angelhunt   File: export_graphdef.py    GNU General Public License v3.0 5 votes vote down vote up
def export_to_tensorflow(request):
    # Note : Remove the views for export by adding unittest for celery tasks
    response = export_json(request, is_tf=True)
    if isinstance(response, JsonResponse):
        return response
    randomId = response['randomId']
    customLayers = response['customLayers']
    os.chdir(BASE_DIR + '/tensorflow_app/views/')
    os.system('KERAS_BACKEND=tensorflow python json2pbtxt.py -input_file ' +
              randomId + '.json -output_file ' + randomId)
    return JsonResponse({'result': 'success',
                         'id': randomId,
                         'name': randomId + '.pbtxt',
                         'url': '/media/' + randomId + '.pbtxt',
                         'customLayers': customLayers}) 
Example 58
Project: reroils-data-legacy   Author: rero   File: test_examples_app.py    GNU General Public License v2.0 5 votes vote down vote up
def example_app():
    """Example app fixture."""
    current_dir = os.getcwd()

    # Go to example directory
    project_dir = dirname(dirname(abspath(__file__)))
    exampleapp_dir = join(project_dir, 'examples')
    os.chdir(exampleapp_dir)

    # Setup application
    assert subprocess.call('./app-setup.sh', shell=True) == 0

    # Setup fixtures
    assert subprocess.call('./app-fixtures.sh', shell=True) == 0

    # Start example app
    webapp = subprocess.Popen(
        'FLASK_APP=app.py flask run --debugger -p 5001',
        stdout=subprocess.PIPE, preexec_fn=os.setsid, shell=True)
    time.sleep(10)
    yield webapp

    # Stop server
    os.killpg(webapp.pid, signal.SIGTERM)

    # Tear down example app
    subprocess.call('./app-teardown.sh', shell=True)

    # Return to the original directory
    os.chdir(current_dir)


# def test_example_app_role_admin(example_app):
#     """Test example app."""
#     cmd = 'curl http://0.0.0.0:5001/'
#     output = subprocess.check_output(cmd, shell=True)
#     assert b'Welcome to REROILS-DATA' in output 
Example 59
Project: voice-recognition   Author: golabies   File: read_data.py    MIT License 5 votes vote down vote up
def __init__(self, fs=44100, channels=1):
        # channels is the Number of microphones
        address = '/'.join(os.getcwd().split('/')[:-1])
        os.chdir(address)
        os.chdir('wave_files')
        self.fs = fs
        self.ch = channels
        self.name = 'out_put'
        self.duration = 5  # second
        self.voice = np.array([]) 
Example 60
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadRemoteClient.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, host="127.0.0.5", port=8888):
        self.socket = socketStream(host, port)
        self.buffer = bufferOut()
        self.stdout = sys.stdout = self.socket
        self.stderr = sys.stderr = self.socket
        self.stdin = sys.stdin
        self.stdOutBuff = PseudoFileOutBuffer(self.buffer)
        self.stdErrBuff = PseudoFileOutBuffer(self.buffer, True)
        sys.stdout=self.stdOutBuff
        sys.stderr=self.stdErrBuff
        self.userLocals = {}
        self.interp = code.InteractiveInterpreter(self.userLocals)
        self.kernelBusy = threading.Event()
        os.chdir(os.path.expanduser("~")) 
Example 61
Project: PyPadPlusPlus   Author: bitagoras   File: pyPadClient.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        self.buffer = bufferOut()
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        self.stdin = sys.stdin
        self.stdOutBuff = PseudoFileOutBuffer(self.buffer)
        self.stdErrBuff = PseudoFileOutBuffer(self.buffer, True)
        sys.stdout=self.stdOutBuff
        sys.stderr=self.stdErrBuff
        self.userLocals = {}
        self.interp = code.InteractiveInterpreter(self.userLocals)
        self.kernelBusy = threading.Event()
        os.chdir(os.path.expanduser("~")) 
Example 62
Project: openplotter   Author: openplotter   File: add_action.py    GNU General Public License v2.0 5 votes vote down vote up
def onSelect(self, e):
		option = self.actions_options[self.action_select.GetCurrentSelection()][0]
		msg = self.actions_options[self.action_select.GetCurrentSelection()][1]
		field = self.actions_options[self.action_select.GetCurrentSelection()][2]
		if field == 0:
			self.data.Disable()
			self.data.SetValue('')
			self.edit_skkey.Disable()
		if field == 1:
			self.data.Enable()
			self.data.SetFocus()
			self.edit_skkey.Enable()
		if msg:
			if msg == 'OpenFileDialog':
				dlg = wx.FileDialog(self, message=_('Choose a file'), defaultDir=self.currentpath + '/sounds',
									defaultFile='',
									wildcard=_('Audio files').decode('utf8') + ' (*.mp3)|*.mp3|' + _('All files').decode('utf8') + ' (*.*)|*.*',
									style=wx.OPEN | wx.CHANGE_DIR)
				if dlg.ShowModal() == wx.ID_OK:
					file_path = dlg.GetPath()
					self.data.SetValue(file_path)
				print self.currentpath
				os.chdir(self.currentpath)			
				dlg.Destroy()
			else:
				if msg == 0:
					pass
				else:
					if field == 1 and option != _('wait'): 
						msg = msg+ _('\n\nYou can add the current value of any Signal K key typing its name between angle brackets, e.g: <navigation.position.latitude>')
					wx.MessageBox(msg, 'Info', wx.OK | wx.ICON_INFORMATION) 
Example 63
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def chdir(d):
    cwd = os.getcwd()
    try:
        os.chdir(d)
        yield
    finally:
        os.chdir(cwd) 
Example 64
Project: GDot   Author: pointhi   File: gdot.py    GNU General Public License v3.0 5 votes vote down vote up
def set_working_dir(self, dir):
        self.open_file_chooser.set_current_folder(dir)
        os.chdir(dir) 
Example 65
Project: payday   Author: lorentzenman   File: payday.py    GNU General Public License v2.0 5 votes vote down vote up
def veil_payloads(ip, output_dir, move_payloads, veil_path, payload_port):
	""" Takes local IP address as LHOST parm and builds Veil payloads"""
	# Veil doesn't have a custom output directory option and the default path gets pulled from the config file
	# hacky approach :: copy each generated payload and handler in to the custom output directory if it is supplied
	# start empty list to hold
	os.chdir(veil_path)
	payloads = []
	# appends payloads with nested 3 value list for dynamic parm calling
	payloads.append(["10",payload_port, "v_revhttps"])
	payloads.append(["5",payload_port,"v_revhttp"])
	payloads.append(["7",payload_port,"v_revmet"])
	payloads.append(["6",payload_port, "v_revhttp_srv"])

	print("Creating Veil Goodness")
	for parms in payloads:
		lhost = ip
		payload = parms[0]
		lport = str(parms[1])
		output = parms[2]
		command = ("./Veil.py -t Evasion -p " + payload + " -c LHOST=" + lhost + " LPORT=" + lport + " -o " + output + " --ip " + ip)
		os.system(command)
		time.sleep(2)
		# if using a custom output directory, veil doesn't have an option to specify the base directory as it gets this from the conf file
		# payload generated above has unique 'base' name - access the list and check the boolean flag that is pushed in
		# if this is true, move the file/handler into the custom output directory so that all payloads are in custom location
		if move_payloads == True:
			# move payload
			os.system("mv /root/payloads/windows/" + output + ".exe "  + output_dir)
			os.system("mv /root/payloads/windows/" + output + ".dll "  + output_dir)
			# move handler
			os.system("mv /root/payloads/windows/handlers/" + output + "_handler.rc " + output_dir + "handlers") 
Example 66
Project: fs_image   Author: facebookincubator   File: demo_sendstreams.py    MIT License 4 votes vote down vote up
def _make_create_ops_subvolume(subvols: TempSubvolumes, path: bytes) -> Subvol:
    'Exercise all the send-stream ops that can occur on a new subvolume.'
    subvol = subvols.create(path)
    run = subvol.run_as_root

    # `cwd` is intentionally prohibited with `run_as_root`
    def p(sv_path):
        return subvol.path(sv_path).decode()

    # Due to an odd `btrfs send` implementation detail, creating a file or
    # directory emits a rename from a temporary name to the final one.
    run(['mkdir', p('hello')])                      # mkdir,rename
    run(['mkdir', p('dir_to_remove')])
    run(['touch', p('hello/world')])                # mkfile,utimes,chmod,chown
    run([                                           # set_xattr
        'setfattr', '-n', 'user.test_attr', '-v', 'chickens', p('hello/'),
    ])
    run(['mknod', p('buffered'), 'b', '1337', '31415'])  # mknod
    run(['chmod', 'og-r', p('buffered')])           # chmod a device
    run(['mknod', p('unbuffered'), 'c', '1337', '31415'])
    run(['mkfifo', p('fifo')])                      # mkfifo
    run(['python3', '-c', (
        'import os, sys, socket as s\n'
        'dir, base = os.path.split(sys.argv[1])\n'
        # Otherwise, we can easily get "AF_UNIX path too long"
        'os.chdir(os.path.join(".", dir))\n'
        'with s.socket(s.AF_UNIX, s.SOCK_STREAM) as sock:\n'
        '    sock.bind(base)\n'                     # mksock
    ), p('unix_sock')])
    run(['ln', p('hello/world'), p('goodbye')])     # link
    run(['ln', '-s', 'hello/world', p('bye_symlink')])  # symlink
    run([                                           # update_extent
        # 56KB was chosen so that `btrfs send` emits more than 1 write,
        # specifically 48KB + 8KB.
        'dd', 'if=/dev/zero', 'of=' + p('56KB_nuls'), 'bs=1024', 'count=56',
    ])
    run([                                           # clone
        'cp', '--reflink=always', p('56KB_nuls'), p('56KB_nuls_clone'),
    ])

    # Make a file with a 16KB hole in the middle.
    run([
        'dd', 'if=/dev/zero', 'of=' + p('zeros_hole_zeros'),
        'bs=1024', 'count=16',
    ])
    run(['truncate', '-s', str(32 * 1024), p('zeros_hole_zeros')])
    run([
        'dd', 'if=/dev/zero', 'of=' + p('zeros_hole_zeros'),
        'oflag=append', 'conv=notrunc', 'bs=1024', 'count=16',
    ])
    # A trailing hole exercises the `truncate` sendstream command.
    run(['bash', '-c', 'echo hello > ' + shlex.quote(p('hello_big_hole'))])
    run(['truncate', '-s', '1G', p('hello_big_hole')])

    # This just serves to show that `btrfs send` ignores nested subvolumes.
    # There is no mention of `nested_subvol` in the send-stream.
    nested_subvol = subvols.create(p('nested_subvol'))
    nested_subvol.run_as_root(['touch', nested_subvol.path('borf')])
    nested_subvol.run_as_root(['mkdir', nested_subvol.path('beep')])

    return subvol 
Example 67
Project: alfred-yubikey-otp   Author: robertoriv   File: background.py    MIT License 4 votes vote down vote up
def _background(pidfile, stdin='/dev/null', stdout='/dev/null',
                stderr='/dev/null'):  # pragma: no cover
    """Fork the current process into a background daemon.

    :param pidfile: file to write PID of daemon process to.
    :type pidfile: filepath
    :param stdin: where to read input
    :type stdin: filepath
    :param stdout: where to write stdout output
    :type stdout: filepath
    :param stderr: where to write stderr output
    :type stderr: filepath

    """
    def _fork_and_exit_parent(errmsg, wait=False, write=False):
        try:
            pid = os.fork()
            if pid > 0:
                if write:  # write PID of child process to `pidfile`
                    tmp = pidfile + '.tmp'
                    with open(tmp, 'wb') as fp:
                        fp.write(str(pid))
                    os.rename(tmp, pidfile)
                if wait:  # wait for child process to exit
                    os.waitpid(pid, 0)
                os._exit(0)
        except OSError as err:
            _log().critical('%s: (%d) %s', errmsg, err.errno, err.strerror)
            raise err

    # Do first fork and wait for second fork to finish.
    _fork_and_exit_parent('fork #1 failed', wait=True)

    # Decouple from parent environment.
    os.chdir(wf().workflowdir)
    os.setsid()

    # Do second fork and write PID to pidfile.
    _fork_and_exit_parent('fork #2 failed', write=True)

    # Now I am a daemon!
    # Redirect standard file descriptors.
    si = open(stdin, 'r', 0)
    so = open(stdout, 'a+', 0)
    se = open(stderr, 'a+', 0)
    if hasattr(sys.stdin, 'fileno'):
        os.dup2(si.fileno(), sys.stdin.fileno())
    if hasattr(sys.stdout, 'fileno'):
        os.dup2(so.fileno(), sys.stdout.fileno())
    if hasattr(sys.stderr, 'fileno'):
        os.dup2(se.fileno(), sys.stderr.fileno()) 
Example 68
Project: pyblish-win   Author: pyblish   File: shutil.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
                 dry_run=0, owner=None, group=None, logger=None):
    """Create an archive file (eg. zip or tar).

    'base_name' is the name of the file to create, minus any format-specific
    extension; 'format' is the archive format: one of "zip", "tar", "bztar"
    or "gztar".

    'root_dir' is a directory that will be the root directory of the
    archive; ie. we typically chdir into 'root_dir' before creating the
    archive.  'base_dir' is the directory where we start archiving from;
    ie. 'base_dir' will be the common prefix of all files and
    directories in the archive.  'root_dir' and 'base_dir' both default
    to the current directory.  Returns the name of the archive file.

    'owner' and 'group' are used when creating a tar archive. By default,
    uses the current owner and group.
    """
    save_cwd = os.getcwd()
    if root_dir is not None:
        if logger is not None:
            logger.debug("changing into '%s'", root_dir)
        base_name = os.path.abspath(base_name)
        if not dry_run:
            os.chdir(root_dir)

    if base_dir is None:
        base_dir = os.curdir

    kwargs = {'dry_run': dry_run, 'logger': logger}

    try:
        format_info = _ARCHIVE_FORMATS[format]
    except KeyError:
        raise ValueError, "unknown archive format '%s'" % format

    func = format_info[0]
    for arg, val in format_info[1]:
        kwargs[arg] = val

    if format != 'zip':
        kwargs['owner'] = owner
        kwargs['group'] = group

    try:
        filename = func(base_name, base_dir, **kwargs)
    finally:
        if root_dir is not None:
            if logger is not None:
                logger.debug("changing back to '%s'", save_cwd)
            os.chdir(save_cwd)

    return filename 
Example 69
Project: pyblish-win   Author: pyblish   File: archive_util.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
                 dry_run=0, owner=None, group=None):
    """Create an archive file (eg. zip or tar).

    'base_name' is the name of the file to create, minus any format-specific
    extension; 'format' is the archive format: one of "zip", "tar", "ztar",
    or "gztar".

    'root_dir' is a directory that will be the root directory of the
    archive; ie. we typically chdir into 'root_dir' before creating the
    archive.  'base_dir' is the directory where we start archiving from;
    ie. 'base_dir' will be the common prefix of all files and
    directories in the archive.  'root_dir' and 'base_dir' both default
    to the current directory.  Returns the name of the archive file.

    'owner' and 'group' are used when creating a tar archive. By default,
    uses the current owner and group.
    """
    save_cwd = os.getcwd()
    if root_dir is not None:
        log.debug("changing into '%s'", root_dir)
        base_name = os.path.abspath(base_name)
        if not dry_run:
            os.chdir(root_dir)

    if base_dir is None:
        base_dir = os.curdir

    kwargs = {'dry_run': dry_run}

    try:
        format_info = ARCHIVE_FORMATS[format]
    except KeyError:
        raise ValueError, "unknown archive format '%s'" % format

    func = format_info[0]
    for arg, val in format_info[1]:
        kwargs[arg] = val

    if format != 'zip':
        kwargs['owner'] = owner
        kwargs['group'] = group

    try:
        filename = func(base_name, base_dir, **kwargs)
    finally:
        if root_dir is not None:
            log.debug("changing back to '%s'", save_cwd)
            os.chdir(save_cwd)

    return filename 
Example 70
Project: pyblish-win   Author: pyblish   File: test_archive_util.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_tarfile_vs_tar(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # now create another tarball using `tar`
        tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
        tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
        gzip_cmd = ['gzip', '-f9', 'archive2.tar']
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            spawn(tar_cmd)
            spawn(gzip_cmd)
        finally:
            os.chdir(old_dir)

        self.assertTrue(os.path.exists(tarball2))
        # let's compare both tarballs
        self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball))

        # now for a dry_run
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            make_tarball(base_name, 'dist', compress=None, dry_run=True)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 71
Project: pyblish-win   Author: pyblish   File: test_bdist_dumb.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_simple_built(self):

        # let's create a simple package
        tmp_dir = self.mkdtemp()
        pkg_dir = os.path.join(tmp_dir, 'foo')
        os.mkdir(pkg_dir)
        self.write_file((pkg_dir, 'setup.py'), SETUP_PY)
        self.write_file((pkg_dir, 'foo.py'), '#')
        self.write_file((pkg_dir, 'MANIFEST.in'), 'include foo.py')
        self.write_file((pkg_dir, 'README'), '')

        dist = Distribution({'name': 'foo', 'version': '0.1',
                             'py_modules': ['foo'],
                             'url': 'xxx', 'author': 'xxx',
                             'author_email': 'xxx'})
        dist.script_name = 'setup.py'
        os.chdir(pkg_dir)

        sys.argv = ['setup.py']
        cmd = bdist_dumb(dist)

        # so the output is the same no matter
        # what is the platform
        cmd.format = 'zip'

        cmd.ensure_finalized()
        cmd.run()

        # see what we have
        dist_created = os.listdir(os.path.join(pkg_dir, 'dist'))
        base = "%s.%s.zip" % (dist.get_fullname(), cmd.plat_name)
        if os.name == 'os2':
            base = base.replace(':', '-')

        self.assertEqual(dist_created, [base])

        # now let's check what we have in the zip file
        fp = zipfile.ZipFile(os.path.join('dist', base))
        try:
            contents = fp.namelist()
        finally:
            fp.close()

        contents = sorted(os.path.basename(fn) for fn in contents)
        wanted = ['foo-0.1-py%s.%s.egg-info' % sys.version_info[:2], 'foo.py']
        if not sys.dont_write_bytecode:
            wanted.append('foo.pyc')
        self.assertEqual(contents, sorted(wanted)) 
Example 72
Project: pyblish-win   Author: pyblish   File: test_shutil.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_tarfile_vs_tar(self):
        tmpdir, tmpdir2, base_name =  self._create_files()
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(base_name, 'dist')
        finally:
            os.chdir(old_dir)

        # check if the compressed tarball was created
        tarball = base_name + '.tar.gz'
        self.assertTrue(os.path.exists(tarball))

        # now create another tarball using `tar`
        tarball2 = os.path.join(tmpdir, 'archive2.tar.gz')
        tar_cmd = ['tar', '-cf', 'archive2.tar', 'dist']
        gzip_cmd = ['gzip', '-f9', 'archive2.tar']
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with captured_stdout() as s:
                spawn(tar_cmd)
                spawn(gzip_cmd)
        finally:
            os.chdir(old_dir)

        self.assertTrue(os.path.exists(tarball2))
        # let's compare both tarballs
        self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))

        # trying an uncompressed one
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(base_name, 'dist', compress=None)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball))

        # now for a dry_run
        base_name = os.path.join(tmpdir2, 'archive')
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            _make_tarball(base_name, 'dist', compress=None, dry_run=True)
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar'
        self.assertTrue(os.path.exists(tarball)) 
Example 73
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_getcwd_long_pathnames(self):
        dirname = 'getcwd-test-directory-0123456789abcdef-01234567890abcdef'
        curdir = os.getcwd()
        base_path = os.path.abspath(test_support.TESTFN) + '.getcwd'

        try:
            os.mkdir(base_path)
            os.chdir(base_path)
        except:
            self.skipTest("cannot create directory for testing")

        try:
            def _create_and_do_getcwd(dirname, current_path_length = 0):
                try:
                    os.mkdir(dirname)
                except:
                    self.skipTest("mkdir cannot create directory sufficiently "
                                  "deep for getcwd test")

                os.chdir(dirname)
                try:
                    os.getcwd()
                    if current_path_length < 4099:
                        _create_and_do_getcwd(dirname, current_path_length + len(dirname) + 1)
                except OSError as e:
                    expected_errno = errno.ENAMETOOLONG
                    # The following platforms have quirky getcwd()
                    # behaviour -- see issue 9185 and 15765 for
                    # more information.
                    quirky_platform = (
                        'sunos' in sys.platform or
                        'netbsd' in sys.platform or
                        'openbsd' in sys.platform
                    )
                    if quirky_platform:
                        expected_errno = errno.ERANGE
                    self.assertEqual(e.errno, expected_errno)
                finally:
                    os.chdir('..')
                    os.rmdir(dirname)

            _create_and_do_getcwd(dirname)

        finally:
            os.chdir(curdir)
            shutil.rmtree(base_path) 
Example 74
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: background.py    MIT License 4 votes vote down vote up
def _background(pidfile, stdin='/dev/null', stdout='/dev/null',
                stderr='/dev/null'):  # pragma: no cover
    """Fork the current process into a background daemon.

    :param pidfile: file to write PID of daemon process to.
    :type pidfile: filepath
    :param stdin: where to read input
    :type stdin: filepath
    :param stdout: where to write stdout output
    :type stdout: filepath
    :param stderr: where to write stderr output
    :type stderr: filepath

    """
    def _fork_and_exit_parent(errmsg, wait=False, write=False):
        try:
            pid = os.fork()
            if pid > 0:
                if write:  # write PID of child process to `pidfile`
                    tmp = pidfile + '.tmp'
                    with open(tmp, 'wb') as fp:
                        fp.write(str(pid))
                    os.rename(tmp, pidfile)
                if wait:  # wait for child process to exit
                    os.waitpid(pid, 0)
                os._exit(0)
        except OSError as err:
            _log().critical('%s: (%d) %s', errmsg, err.errno, err.strerror)
            raise err

    # Do first fork and wait for second fork to finish.
    _fork_and_exit_parent('fork #1 failed', wait=True)

    # Decouple from parent environment.
    os.chdir(wf().workflowdir)
    os.setsid()

    # Do second fork and write PID to pidfile.
    _fork_and_exit_parent('fork #2 failed', write=True)

    # Now I am a daemon!
    # Redirect standard file descriptors.
    si = open(stdin, 'r', 0)
    so = open(stdout, 'a+', 0)
    se = open(stderr, 'a+', 0)
    if hasattr(sys.stdin, 'fileno'):
        os.dup2(si.fileno(), sys.stdin.fileno())
    if hasattr(sys.stdout, 'fileno'):
        os.dup2(so.fileno(), sys.stdout.fileno())
    if hasattr(sys.stderr, 'fileno'):
        os.dup2(se.fileno(), sys.stderr.fileno()) 
Example 75
Project: prediction-constrained-topic-models   Author: dtak   File: utils_snapshots.py    MIT License 4 votes vote down vote up
def download_snapshot(
        snapshot_path=None,
        rsync_path=None,
        local_path=None,
        remote_path=None,
        ):
    if local_path is None:
        try:
            local_path = os.environ['XHOST_LOCAL_PATH']
        except KeyError:
            raise ValueError("Bad value for local_path: %s" % local_path)
    if remote_path is None:
        try:
            remote_path = os.environ['XHOST_REMOTE_PATH']
        except KeyError:
            raise ValueError("Bad value for remote_path: %s" % remote_path)
    if rsync_path is None:
        try:
            rsync_path = os.environ['XHOST_RSYNC_PATH']
        except KeyError:
            rsync_path = os.path.expandvars("$PC_REPO_DIR/scripts/rsync_tools/")
    if not os.path.exists(rsync_path):
        raise ValueError("Bad value for rsync_path: %s" % rsync_path)

    local_path = os.path.abspath(local_path)
    remote_path = os.path.abspath(remote_path)
    if snapshot_path.count(local_path):
        local_snapshot_path = snapshot_path
        remote_snapshot_path = snapshot_path.replace(local_path, remote_path)
    elif snapshot_path.count(remote_path):
        remote_snapshot_path = snapshot_path
        local_snapshot_path = snapshot_path.replace(remote_path, local_path)
    else:
        raise ValueError("Bad snapshot_path:\n%s" % snapshot_path)

    old_path = os.getcwd()
    print("cd %s" % rsync_path)
    os.chdir(rsync_path)
    cmd_str = "bash rsync_specific_snapshot.sh %s" % remote_snapshot_path
    print("ATTEMPTING DOWNLOAD via CUSTOM RSYNC CMD:")
    print(cmd_str)
    ans = os.system(cmd_str)
    print("cd %s" % old_path)
    os.chdir(old_path)
    if int(str(ans)) != 0:
        raise ValueError("BAD DOWNLOAD: ANSWER CODE %s" % ans)
    return True 
Example 76
Project: ieml   Author: IEMLdev   File: migrate_v02Tov03.py    GNU General Public License v3.0 4 votes vote down vote up
def migrate(db, author_name, author_mail):
    folder = db.folder

    # print(paths)

    old_p_desc = os.path.join(folder, 'descriptors/dictionary')
    new_p_desc = os.path.join(folder, 'descriptors')


    old_p_struct = os.path.join(folder, 'structure/dictionary')
    # new_p_struct = os.path.join(folder, 'dictionary/structure')

    # os.mkdir(os.path.join(folder, 'dictionary'))
    # shutil.copy(old_p_desc, new_p_desc)
    # shutil.copy(old_p_struct, new_p_struct)

    dictionary = db.dictionary()
    descriptors = DescriptorSet.from_file(os.path.join(db.folder, 'descriptors/dictionary'))

    lexicon_folder = os.path.join(db.folder, 'lexicons')
    shutil.rmtree(lexicon_folder)
    lexicon_folder = os.path.join(db.folder, 'structure/lexicons')
    os.mkdir(lexicon_folder)

    # os.mkdir(lexicon_folder)
    df = descriptors.descriptors.reset_index()
    df.rename(columns={'script': 'ieml'}, inplace=True)

    lex = LexiconStructure()
    desc = LexiconDescriptorSet(df)
    import_old_series(lex, desc, dictionary)

    lex.write_to_folder(lexicon_folder)
    desc.write_to_folder(folder)


    with open(os.path.join(folder, 'version'), 'w') as fp:
        fp.write('0.3')
    from glob import glob
    os.chdir(folder)
    descriptors_paths = [f[2:] for f in glob('./descriptors/**', recursive=True) if os.path.isfile(f) and
                         not f.endswith('dictionary')]
    structure_path = [f[2:] for f in glob('./structure/**', recursive=True) if os.path.isfile(f)]

    old_lexicon_files = [f[2:] for f in glob('./lexicons/**', recursive=True) if os.path.isfile(f)]

    db.save_changes(author_name, author_mail,
                    "[dictionary] Migrate to format v03",
                    to_add=[*descriptors_paths, 'version', *structure_path],
                    to_remove=['descriptors/dictionary', *old_lexicon_files],
                    check_coherency=True)

    # shutil.rmtree(os.path.join(folder, 'lexicons'))
    # shutil.rmtree(os.path.join(folder, 'descriptors/dictionary')) 
Example 77
Project: twiml-generator   Author: TwilioDevEd   File: twiml_code_generator.py    MIT License 4 votes vote down vote up
def verify_csharp(self):
        if not shutil.which('dotnet'):
            raise Exception('You need to install dotnet core if you want to verify a C# file')

        is_new_env = False
        cwd = Path.cwd()
        absolute_code_filepath = self.code_filepath.resolve()
        project_filepath = Path('dotnet_env')
        if not project_filepath.exists():
            project_filepath.mkdir()
            is_new_env = True
        os.chdir(project_filepath)

        def csharp_clean():
            try:
                os.chdir(cwd)
            except OSError:
                pass

        dotnet_new_command = ['dotnet', 'new', 'console']
        dotnet_add_package_command = ['dotnet', 'add', 'package', 'Twilio']
        dotnet_run_command = ['dotnet', 'run']

        if is_new_env:
            logger.debug('Running: {}'.format(' '.join(dotnet_new_command)))
            p = subprocess.run(dotnet_new_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if p.returncode != 0:
                csharp_clean()
                return p

            logger.debug('Running: {}'.format(' '.join(dotnet_add_package_command)))
            p = subprocess.run(dotnet_add_package_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            if p.returncode != 0:
                csharp_clean()
                return p

        program_path = Path('Program.cs')
        program_path.unlink()
        program_path.symlink_to(absolute_code_filepath)

        logger.debug('Running: {}'.format(' '.join(dotnet_run_command)))
        p = subprocess.run(dotnet_run_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        csharp_clean()
        return p 
Example 78
Project: kuaa   Author: rafaelwerneck   File: plugin_cedd.py    GNU General Public License v3.0 4 votes vote down vote up
def distance(fv1, fv2):
    """
    Performs the calculation of distance between the two feature vectors,
    according to the Distance function of the executable.
    
    Inputs:
        - fv1 (list of floats): First feature vector
        - fv2 (list of floats): Second feature vector
    
    Output:
        - distance (double): Distance between the two feature vectors
    """
    
    #Imports
    import subprocess
    import xml.etree.cElementTree as ET
    from ast import literal_eval
    
    #Get parameters
    xml_name = os.path.join("Experiment " + experiment_id, "experiment.xml")
    xml_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..",
                                            "..", "experiments", xml_name))
    xml_file = ET.parse(xml_path)
    xml_desc = xml_file.findall("descriptor")
    for descriptor in xml_desc:
        if descriptor.attrib["name"] == "cedd":
            param = literal_eval(descriptor.get("parameters"))
            break
    
    #Change the current directory to the directory of the files
    orig_dir = os.getcwd()
    os.chdir(os.path.dirname(__file__))
    
    jython_args = ['jython', 'jython_cedd.py', 'Distance']
    jython_args.append(str(fv1))
    jython_args.append(str(fv2))
    jython_args.append(str(param))
    
    #Descriptor exclusive
    #-------------------------------------------------------------------------
    cedd_process = subprocess.Popen(jython_args, stdout=subprocess.PIPE)
    print "\t", cedd_process
    cedd_distance = cedd_process.communicate()[0]
    cedd_process.wait()
    distance = float(cedd_distance)
    
    #Return to the original directory
    os.chdir(orig_dir)
    #-------------------------------------------------------------------------
    
    return distance 
Example 79
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: recompiler.py    MIT License 4 votes vote down vote up
def recompile(ffi, module_name, preamble, tmpdir='.', call_c_compiler=True,
              c_file=None, source_extension='.c', extradir=None,
              compiler_verbose=1, target=None, debug=None, **kwds):
    if not isinstance(module_name, str):
        module_name = module_name.encode('ascii')
    if ffi._windows_unicode:
        ffi._apply_windows_unicode(kwds)
    if preamble is not None:
        embedding = (ffi._embedding is not None)
        if embedding:
            ffi._apply_embedding_fix(kwds)
        if c_file is None:
            c_file, parts = _modname_to_file(tmpdir, module_name,
                                             source_extension)
            if extradir:
                parts = [extradir] + parts
            ext_c_file = os.path.join(*parts)
        else:
            ext_c_file = c_file
        #
        if target is None:
            if embedding:
                target = '%s.*' % module_name
            else:
                target = '*'
        #
        ext = ffiplatform.get_extension(ext_c_file, module_name, **kwds)
        updated = make_c_source(ffi, module_name, preamble, c_file,
                                verbose=compiler_verbose)
        if call_c_compiler:
            patchlist = []
            cwd = os.getcwd()
            try:
                if embedding:
                    _patch_for_embedding(patchlist)
                if target != '*':
                    _patch_for_target(patchlist, target)
                if compiler_verbose:
                    if tmpdir == '.':
                        msg = 'the current directory is'
                    else:
                        msg = 'setting the current directory to'
                    print('%s %r' % (msg, os.path.abspath(tmpdir)))
                os.chdir(tmpdir)
                outputfilename = ffiplatform.compile('.', ext,
                                                     compiler_verbose, debug)
            finally:
                os.chdir(cwd)
                _unpatch_meths(patchlist)
            return outputfilename
        else:
            return ext, updated
    else:
        if c_file is None:
            c_file, _ = _modname_to_file(tmpdir, module_name, '.py')
        updated = make_py_source(ffi, module_name, c_file,
                                 verbose=compiler_verbose)
        if call_c_compiler:
            return c_file
        else:
            return None, updated 
Example 80
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: shutil.py    MIT License 4 votes vote down vote up
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
                 dry_run=0, owner=None, group=None, logger=None):
    """Create an archive file (eg. zip or tar).

    'base_name' is the name of the file to create, minus any format-specific
    extension; 'format' is the archive format: one of "zip", "tar", "bztar"
    or "gztar".

    'root_dir' is a directory that will be the root directory of the
    archive; ie. we typically chdir into 'root_dir' before creating the
    archive.  'base_dir' is the directory where we start archiving from;
    ie. 'base_dir' will be the common prefix of all files and
    directories in the archive.  'root_dir' and 'base_dir' both default
    to the current directory.  Returns the name of the archive file.

    'owner' and 'group' are used when creating a tar archive. By default,
    uses the current owner and group.
    """
    save_cwd = os.getcwd()
    if root_dir is not None:
        if logger is not None:
            logger.debug("changing into '%s'", root_dir)
        base_name = os.path.abspath(base_name)
        if not dry_run:
            os.chdir(root_dir)

    if base_dir is None:
        base_dir = os.curdir

    kwargs = {'dry_run': dry_run, 'logger': logger}

    try:
        format_info = _ARCHIVE_FORMATS[format]
    except KeyError:
        raise ValueError("unknown archive format '%s'" % format)

    func = format_info[0]
    for arg, val in format_info[1]:
        kwargs[arg] = val

    if format != 'zip':
        kwargs['owner'] = owner
        kwargs['group'] = group

    try:
        filename = func(base_name, base_dir, **kwargs)
    finally:
        if root_dir is not None:
            if logger is not None:
                logger.debug("changing back to '%s'", save_cwd)
            os.chdir(save_cwd)

    return filename