Python os.getcwd() Examples

The following are code examples for showing how to use os.getcwd(). 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: f5go   Author: f5devcentral   File: go.py    MIT License 7 votes vote down vote up
def main():
    cherrypy.config.update({'server.socket_host': '::',
                            'server.socket_port': cfg_port,
                            'request.query_string_encoding': "latin1",
                            })

    cherrypy.https = s = cherrypy._cpserver.Server()
    if cfg_sslEnabled:
        s.socket_host = '::'
        s.socket_port = 443
        s.ssl_certificate = cfg_sslCertificate
        s.ssl_private_key = cfg_sslPrivateKey
        s.subscribe()

    # checkpoint the database every 60 seconds
    cherrypy.process.plugins.BackgroundTask(60, lambda: g_db.save()).start()

    file_path = os.getcwd().replace("\\", "/")
    conf = {'/images': {"tools.staticdir.on": True, "tools.staticdir.dir": file_path + "/images"},
            '/css': {"tools.staticdir.on": True, "tools.staticdir.dir": file_path + "/css"},
            '/js': {"tools.staticdir.on": True, "tools.staticdir.dir": file_path + "/js"}}
    print("Cherrypy conf: %s" % conf)
    cherrypy.quickstart(Root(), "/", config=conf) 
Example 2
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    MIT License 7 votes vote down vote up
def find_executable(name) -> str:
    is_windows = os.name == 'nt'
    windows_exts = ENV_PATH_SEP.split(os.environ['PATHEXT']) if is_windows else None
    path_dirs = ENV_PATH_SEP.split(os.environ['PATH'])

    search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list

    for dir in search_dirs:
        path = os.path.join(dir, name)

        if is_windows:
            for extension in windows_exts:
                path_with_ext = path + extension

                if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
                    return path_with_ext
        else:
            if os.path.isfile(path) and os.access(path, os.X_OK):
                return path

    return '' 
Example 3
Project: pyblish-win   Author: pyblish   File: test_discovery.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_discover_with_modules_that_fail_to_import(self):
        loader = unittest.TestLoader()

        listdir = os.listdir
        os.listdir = lambda _: ['test_this_does_not_exist.py']
        isfile = os.path.isfile
        os.path.isfile = lambda _: True
        orig_sys_path = sys.path[:]
        def restore():
            os.path.isfile = isfile
            os.listdir = listdir
            sys.path[:] = orig_sys_path
        self.addCleanup(restore)

        suite = loader.discover('.')
        self.assertIn(os.getcwd(), sys.path)
        self.assertEqual(suite.countTestCases(), 1)
        test = list(list(suite)[0])[0] # extract test from suite

        with self.assertRaises(ImportError):
            test.test_this_does_not_exist() 
Example 4
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_basic(self):
        b = """os.getcwdu"""
        a = """os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu()"""
        a = """os.getcwd()"""
        self.check(b, a)

        b = """meth = os.getcwdu"""
        a = """meth = os.getcwd"""
        self.check(b, a)

        b = """os.getcwdu(args)"""
        a = """os.getcwd(args)"""
        self.check(b, a) 
Example 5
Project: pyblish-win   Author: pyblish   File: SimpleHTTPServer.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def translate_path(self, path):
        """Translate a /-separated PATH to the local filename syntax.

        Components that mean special things to the local file system
        (e.g. drive or directory names) are ignored.  (XXX They should
        probably be diagnosed.)

        """
        # abandon query parameters
        path = path.split('?',1)[0]
        path = path.split('#',1)[0]
        # Don't forget explicit trailing slash when normalizing. Issue17324
        trailing_slash = path.rstrip().endswith('/')
        path = posixpath.normpath(urllib.unquote(path))
        words = path.split('/')
        words = filter(None, words)
        path = os.getcwd()
        for word in words:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir): continue
            path = os.path.join(path, word)
        if trailing_slash:
            path += '/'
        return path 
Example 6
Project: pyblish-win   Author: pyblish   File: test_core.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_run_setup_uses_current_dir(self):
        # This tests that the setup script is run with the current directory
        # as its own current directory; this was temporarily broken by a
        # previous patch when TESTFN did not use the current directory.
        sys.stdout = StringIO.StringIO()
        cwd = os.getcwd()

        # Create a directory and write the setup.py file there:
        os.mkdir(test.test_support.TESTFN)
        setup_py = os.path.join(test.test_support.TESTFN, "setup.py")
        distutils.core.run_setup(
            self.write_setup(setup_prints_cwd, path=setup_py))

        output = sys.stdout.getvalue()
        if output.endswith("\n"):
            output = output[:-1]
        self.assertEqual(cwd, output) 
Example 7
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 8
Project: pyblish-win   Author: pyblish   File: test_ntpath.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_relpath(self):
        currentdir = os.path.split(os.getcwd())[-1]
        tester('ntpath.relpath("a")', 'a')
        tester('ntpath.relpath(os.path.abspath("a"))', 'a')
        tester('ntpath.relpath("a/b")', 'a\\b')
        tester('ntpath.relpath("../a/b")', '..\\a\\b')
        tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
        tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
        tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
        tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
        tester('ntpath.relpath("a", "a")', '.')
        tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat')
        tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
        tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
        tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
        tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
        tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
        tester('ntpath.relpath("/", "/")', '.')
        tester('ntpath.relpath("/a", "/a")', '.')
        tester('ntpath.relpath("/a/b", "/a/b")', '.')
        tester('ntpath.relpath("c:/foo", "C:/FOO")', '.') 
Example 9
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extract(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                writtenfile = zipfp.extract(fpath)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fpath)
                correctfile = os.path.normpath(correctfile)

                self.assertEqual(writtenfile, correctfile)

                # make sure correct data is in correct file
                with open(writtenfile, "rb") as fid:
                    self.assertEqual(fdata, fid.read())
                os.remove(writtenfile)

        # remove the test file subdirectories
        rmtree(os.path.join(os.getcwd(), 'ziptest2dir')) 
Example 10
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extract_all(self):
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fpath, fdata in SMALL_TEST_DATA:
                zipfp.writestr(fpath, fdata)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            zipfp.extractall()
            for fpath, fdata in SMALL_TEST_DATA:
                outfile = os.path.join(os.getcwd(), fpath)

                with open(outfile, "rb") as fid:
                    self.assertEqual(fdata, fid.read())
                os.remove(outfile)

        # remove the test file subdirectories
        rmtree(os.path.join(os.getcwd(), 'ziptest2dir')) 
Example 11
Project: pyblish-win   Author: pyblish   File: test_zipfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_extract_unicode_filenames(self):
        fnames = [u'foo.txt', os.path.basename(TESTFN_UNICODE)]
        content = 'Test for unicode filename'
        with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
            for fname in fnames:
                zipfp.writestr(fname, content)

        with zipfile.ZipFile(TESTFN2, "r") as zipfp:
            for fname in fnames:
                writtenfile = zipfp.extract(fname)

                # make sure it was written to the right place
                correctfile = os.path.join(os.getcwd(), fname)
                correctfile = os.path.normpath(correctfile)
                self.assertEqual(writtenfile, correctfile)

                self.check_file(writtenfile, content)
                os.remove(writtenfile) 
Example 12
Project: pyblish-win   Author: pyblish   File: test_tarfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_cwd(self):
        # Test adding the current working directory.
        cwd = os.getcwd()
        os.chdir(TEMPDIR)
        try:
            open("foo", "w").close()

            tar = tarfile.open(tmpname, self.mode)
            tar.add(".")
            tar.close()

            tar = tarfile.open(tmpname, "r")
            for t in tar:
                self.assertTrue(t.name == "." or t.name.startswith("./"))
            tar.close()
        finally:
            os.chdir(cwd) 
Example 13
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 14
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 15
Project: pyblish-win   Author: pyblish   File: test_posix.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testNoArgFunctions(self):
        # test posix functions which take no arguments and have
        # no side-effects which we need to cleanup (e.g., fork, wait, abort)
        NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdu", "uname",
                             "times", "getloadavg", "tmpnam",
                             "getegid", "geteuid", "getgid", "getgroups",
                             "getpid", "getpgrp", "getppid", "getuid",
                           ]

        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", "", DeprecationWarning)
            for name in NO_ARG_FUNCTIONS:
                posix_func = getattr(posix, name, None)
                if posix_func is not None:
                    posix_func()
                    self.assertRaises(TypeError, posix_func, 1) 
Example 16
Project: pyblish-win   Author: pyblish   File: configHelpSourceEdit.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def browseFile(self):
        filetypes = [
            ("HTML Files", "*.htm *.html", "TEXT"),
            ("PDF Files", "*.pdf", "TEXT"),
            ("Windows Help Files", "*.chm"),
            ("Text Files", "*.txt", "TEXT"),
            ("All Files", "*")]
        path = self.path.get()
        if path:
            dir, base = os.path.split(path)
        else:
            base = None
            if sys.platform[:3] == 'win':
                dir = os.path.join(os.path.dirname(sys.executable), 'Doc')
                if not os.path.isdir(dir):
                    dir = os.getcwd()
            else:
                dir = os.getcwd()
        opendialog = tkFileDialog.Open(parent=self, filetypes=filetypes)
        file = opendialog.show(initialdir=dir, initialfile=base)
        if file:
            self.path.set(file) 
Example 17
Project: RelayBot2.0   Author: nukeop   File: logs.py    GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, bot):
        super(Logs, self).__init__(bot)
        self.loggers = {}
        self.logs_path = os.path.join(os.getcwd(), "logs")
        self.friend_logs_path = os.path.join(self.logs_path, "friends")
        self.group_logs_path = os.path.join(self.logs_path, "groups")

        try:
            os.makedirs(self.friend_logs_path)
        except OSError:
            logger.error("Could not create {}".format(self.friend_logs_path))

        try:
            os.makedirs(self.group_logs_path)
        except OSError:
            logger.error("Could not create {}".format(self.group_logs_path)) 
Example 18
Project: tom-bot   Author: maartenberg   File: layer.py    MIT License 5 votes vote down vote up
def __init__(self, config, scheduler):
        super(self.__class__, self).__init__()
        self.connected = False
        self.config = config
        self.scheduler = scheduler
        logging.info('Current working directory: %s', os.getcwd())
        try:
            logging.info('Database location: %s',
                         config['Yowsup']['database'])
            self.conn = sqlite3.connect(config['Yowsup']['database'],
                                        detect_types=sqlite3.PARSE_DECLTYPES,
                                        check_same_thread=False)
            self.conn.text_factory = str
            self.cursor = self.conn.cursor()
        except KeyError:
            logging.critical('Database could not be loaded!')

        # Group list holder
        self.known_groups = []

        # Start rpc listener
        host = 'localhost'
        port = 10666
        self.rpcserver = rpc.ThreadedTCPServer((host, port), rpc.ThreadedTCPRequestHandler, self)

        server_thread = threading.Thread(target=self.rpcserver.serve_forever)
        server_thread.daemon = True
        server_thread.start()

        # Start the passed scheduler
        self.scheduler.start()

        self.functions = {}
        plugins.load_plugins()
        self.functions.update(registry.COMMAND_DICT)

        # Execute startup hooks
        registry.fire_event(registry.BOT_START, self) 
Example 19
Project: phrydy   Author: Josef-Friedrich   File: versioneer.py    MIT License 5 votes vote down vote up
def get_root():
    """Get the project root directory.

    We require that all commands are run from the project root, i.e. the
    directory that contains setup.py, setup.cfg, and versioneer.py .
    """
    root = os.path.realpath(os.path.abspath(os.getcwd()))
    setup_py = os.path.join(root, "setup.py")
    versioneer_py = os.path.join(root, "versioneer.py")
    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
        # allow 'python path/to/setup.py COMMAND'
        root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
        setup_py = os.path.join(root, "setup.py")
        versioneer_py = os.path.join(root, "versioneer.py")
    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
        err = ("Versioneer was unable to run the project root directory. "
               "Versioneer requires setup.py to be executed from "
               "its immediate directory (like 'python setup.py COMMAND'), "
               "or in a way that lets it use sys.argv[0] to find the root "
               "(like 'python path/to/setup.py COMMAND').")
        raise VersioneerBadRootError(err)
    try:
        # Certain runtime workflows (setup.py install/develop in a setuptools
        # tree) execute all dependencies in a single python process, so
        # "versioneer" may be imported multiple times, and python's shared
        # module-import table will cache the first one. So we can't use
        # os.path.dirname(__file__), as that will find whichever
        # versioneer.py was first imported, even in later projects.
        me = os.path.realpath(os.path.abspath(__file__))
        me_dir = os.path.normcase(os.path.splitext(me)[0])
        vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
        if me_dir != vsr_dir:
            print("Warning: build in %s is using versioneer.py from %s"
                  % (os.path.dirname(me), versioneer_py))
    except NameError:
        pass
    return root 
Example 20
Project: client   Author: Scorched-Moon   File: dialog.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, title_txt="File Browser", button_txt="Okay", cls="dialog", path=None):
        """FileDialog constructor.

        Keyword arguments:
            title_txt -- title text
            button_txt -- button text
            path -- initial path

        """

        cls1 = "filedialog"
        if not path: self.curdir = os.getcwd()
        else: self.curdir = path
        self.dir_img = basic.Image(
            pguglobals.app.theme.get(cls1+".folder", "", 'image'))
        td_style = {'padding_left': 4,
                    'padding_right': 4,
                    'padding_top': 2,
                    'padding_bottom': 2}
        self.title = basic.Label(title_txt, cls=cls+".title.label")
        self.body = table.Table()
        self.list = area.List(width=350, height=150)
        self.input_dir = input.Input()
        self.input_file = input.Input()
        self._list_dir_()
        self.button_ok = button.Button(button_txt)
        self.body.tr()
        self.body.td(basic.Label("Folder"), style=td_style, align=-1)
        self.body.td(self.input_dir, style=td_style)
        self.body.tr()
        self.body.td(self.list, colspan=3, style=td_style)
        self.list.connect(CHANGE, self._item_select_changed_, None)
        self.button_ok.connect(CLICK, self._button_okay_clicked_, None)
        self.body.tr()
        self.body.td(basic.Label("File"), style=td_style, align=-1)
        self.body.td(self.input_file, style=td_style)
        self.body.td(self.button_ok, style=td_style)
        self.value = None
        Dialog.__init__(self, self.title, self.body) 
Example 21
Project: pyblish-win   Author: pyblish   File: dist.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def exe(src, dst):
    """Create installer using Inno Setup

    Arguments:
        src (str): Path to bundle, e.g. /build
        dst (str): Output directory in which to compile installer, e.g. /dist

    """

    print("Creating installer..")
    try:
        iscc = subprocess.check_output(["where", "iscc"]).strip()
    except subprocess.CalledProcessError:
        print("Could not find Inno Setup")
        return 1

    setup = os.path.join(os.getcwd(), "setup.iss")

    print("Compiling \"%s\" using \"%s\"" % (setup, iscc))
    BUILD = os.environ.get("APPVEYOR_BUILD_NUMBER", "0")
    VERSION = os.path.join(__file__, "..", "..", "lib", "pyblish", "VERSION")
    with open(VERSION) as f:
        VERSION = f.read()

    subprocess.call([iscc,
                     "/dMyVersion=%s-build%s" % (VERSION, BUILD),
                     "/dMyOutputDir=%s" % dst,
                     setup])

    print("Successfully created installer") 
Example 22
Project: pyblish-win   Author: pyblish   File: tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _candidate_tempdir_list():
    """Generate a list of candidate temporary directories which
    _get_default_tempdir will try."""

    dirlist = []

    # First, try the environment.
    for envname in 'TMPDIR', 'TEMP', 'TMP':
        dirname = _os.getenv(envname)
        if dirname: dirlist.append(dirname)

    # Failing that, try OS-specific locations.
    if _os.name == 'riscos':
        dirname = _os.getenv('Wimp$ScrapDir')
        if dirname: dirlist.append(dirname)
    elif _os.name == 'nt':
        dirlist.extend([ r'c:\temp', r'c:\tmp', r'\temp', r'\tmp' ])
    else:
        dirlist.extend([ '/tmp', '/var/tmp', '/usr/tmp' ])

    # As a last resort, the current directory.
    try:
        dirlist.append(_os.getcwd())
    except (AttributeError, _os.error):
        dirlist.append(_os.curdir)

    return dirlist 
Example 23
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_comment(self):
        b = """os.getcwdu() # Foo"""
        a = """os.getcwd() # Foo"""
        self.check(b, a) 
Example 24
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_indentation(self):
        b = """
            if 1:
                os.getcwdu()
            """
        a = """
            if 1:
                os.getcwd()
            """
        self.check(b, a) 
Example 25
Project: pyblish-win   Author: pyblish   File: test_fixers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_multilation(self):
        b = """os .getcwdu()"""
        a = """os .getcwd()"""
        self.check(b, a)

        b = """os.  getcwdu"""
        a = """os.  getcwd"""
        self.check(b, a)

        b = """os.getcwdu (  )"""
        a = """os.getcwd (  )"""
        self.check(b, a) 
Example 26
Project: pyblish-win   Author: pyblish   File: macpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def abspath(path):
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

# realpath is a no-op on systems without islink support 
Example 27
Project: pyblish-win   Author: pyblish   File: ntpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def abspath(path):
        """Return the absolute version of a path."""

        if path: # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except WindowsError:
                pass # Bad path - return unchanged.
        elif isinstance(path, unicode):
            path = os.getcwdu()
        else:
            path = os.getcwd()
        return normpath(path)

# realpath is a no-op on systems without islink support 
Example 28
Project: pyblish-win   Author: pyblish   File: cgi.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def print_directory():
    """Dump the current directory as HTML."""
    print
    print "<H3>Current Working Directory:</H3>"
    try:
        pwd = os.getcwd()
    except os.error, msg:
        print "os.error:", escape(str(msg)) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_build_ext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ext_fullpath(self):
        ext = sysconfig.get_config_vars()['SO']
        dist = Distribution()
        cmd = build_ext(dist)
        cmd.inplace = 1
        cmd.distribution.package_dir = {'': 'src'}
        cmd.distribution.packages = ['lxml', 'lxml.html']
        curdir = os.getcwd()
        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
        path = cmd.get_ext_fullpath('lxml.etree')
        self.assertEqual(wanted, path)

        # building lxml.etree not inplace
        cmd.inplace = 0
        cmd.build_lib = os.path.join(curdir, 'tmpdir')
        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
        path = cmd.get_ext_fullpath('lxml.etree')
        self.assertEqual(wanted, path)

        # building twisted.runner.portmap not inplace
        build_py = cmd.get_finalized_command('build_py')
        build_py.package_dir = {}
        cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
        path = cmd.get_ext_fullpath('twisted.runner.portmap')
        wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
                              'portmap' + ext)
        self.assertEqual(wanted, path)

        # building twisted.runner.portmap inplace
        cmd.inplace = 1
        path = cmd.get_ext_fullpath('twisted.runner.portmap')
        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
        self.assertEqual(wanted, path) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_build_ext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_build_ext_inplace(self):
        etree_c = os.path.join(self.tmp_dir, 'lxml.etree.c')
        etree_ext = Extension('lxml.etree', [etree_c])
        dist = Distribution({'name': 'lxml', 'ext_modules': [etree_ext]})
        cmd = build_ext(dist)
        cmd.ensure_finalized()
        cmd.inplace = 1
        cmd.distribution.package_dir = {'': 'src'}
        cmd.distribution.packages = ['lxml', 'lxml.html']
        curdir = os.getcwd()
        ext = sysconfig.get_config_var("SO")
        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
        path = cmd.get_ext_fullpath('lxml.etree')
        self.assertEqual(wanted, path) 
Example 31
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 32
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 33
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 34
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_make_archive_cwd(self):
        current_dir = os.getcwd()
        def _breaks(*args, **kw):
            raise RuntimeError()
        ARCHIVE_FORMATS['xxx'] = (_breaks, [], 'xxx file')
        try:
            try:
                make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
            except:
                pass
            self.assertEqual(os.getcwd(), current_dir)
        finally:
            del ARCHIVE_FORMATS['xxx'] 
Example 35
Project: pyblish-win   Author: pyblish   File: support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(TempdirManager, self).setUp()
        self.old_cwd = os.getcwd()
        self.tempdirs = [] 
Example 36
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 37
Project: pyblish-win   Author: pyblish   File: test_bdist_rpm.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        super(BuildRpmTestCase, self).setUp()
        self.old_location = os.getcwd()
        self.old_sys_argv = sys.argv, sys.argv[:] 
Example 38
Project: pyblish-win   Author: pyblish   File: turtle.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def readconfig(cfgdict):
    """Read config-files, change configuration-dict accordingly.

    If there is a turtle.cfg file in the current working directory,
    read it from there. If this contains an importconfig-value,
    say 'myway', construct filename turtle_mayway.cfg else use
    turtle.cfg and read it from the import-directory, where
    turtle.py is located.
    Update configuration dictionary first according to config-file,
    in the import directory, then according to config-file in the
    current working directory.
    If no config-file is found, the default configuration is used.
    """
    default_cfg = "turtle.cfg"
    cfgdict1 = {}
    cfgdict2 = {}
    if isfile(default_cfg):
        cfgdict1 = config_dict(default_cfg)
        #print "1. Loading config-file %s from: %s" % (default_cfg, os.getcwd())
    if "importconfig" in cfgdict1:
        default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"]
    try:
        head, tail = split(__file__)
        cfg_file2 = join(head, default_cfg)
    except:
        cfg_file2 = ""
    if isfile(cfg_file2):
        #print "2. Loading config-file %s:" % cfg_file2
        cfgdict2 = config_dict(cfg_file2)
##    show(_CFG)
##    show(cfgdict2)
    _CFG.update(cfgdict2)
##    show(_CFG)
##    show(cfgdict1)
    _CFG.update(cfgdict1)
##    show(_CFG) 
Example 39
Project: pyblish-win   Author: pyblish   File: FileDialog.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_filter(self, dir, pat):
        if not os.path.isabs(dir):
            try:
                pwd = os.getcwd()
            except os.error:
                pwd = None
            if pwd:
                dir = os.path.join(pwd, dir)
                dir = os.path.normpath(dir)
        self.filter.delete(0, END)
        self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) 
Example 40
Project: pyblish-win   Author: pyblish   File: platform.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _abspath(path,

                 isabs=os.path.isabs,join=os.path.join,getcwd=os.getcwd,
                 normpath=os.path.normpath):

        if not isabs(path):
            path = join(getcwd(), path)
        return normpath(path) 
Example 41
Project: pyblish-win   Author: pyblish   File: zipfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def extract(self, member, path=None, pwd=None):
        """Extract a member from the archive to the current working directory,
           using its full name. Its file information is extracted as accurately
           as possible. `member' may be a filename or a ZipInfo object. You can
           specify a different directory using `path'.
        """
        if not isinstance(member, ZipInfo):
            member = self.getinfo(member)

        if path is None:
            path = os.getcwd()

        return self._extract_member(member, path, pwd) 
Example 42
Project: pyblish-win   Author: pyblish   File: regrtest.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_cwd(self):
        return os.getcwd() 
Example 43
Project: pyblish-win   Author: pyblish   File: test_support.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def temp_cwd(name='tempcwd', quiet=False):
    """
    Context manager that creates a temporary directory and set it as CWD.

    The new CWD is created in the current directory and it's named *name*.
    If *quiet* is False (default) and it's not possible to create or change
    the CWD, an error is raised.  If it's True, only a warning is raised
    and the original CWD is used.
    """
    if have_unicode and isinstance(name, unicode):
        try:
            name = name.encode(sys.getfilesystemencoding() or 'ascii')
        except UnicodeEncodeError:
            if not quiet:
                raise unittest.SkipTest('unable to encode the cwd name with '
                                        'the filesystem encoding.')
    saved_dir = os.getcwd()
    is_temporary = False
    try:
        os.mkdir(name)
        os.chdir(name)
        is_temporary = True
    except OSError:
        if not quiet:
            raise
        warnings.warn('tests may fail, unable to change the CWD to ' + name,
                      RuntimeWarning, stacklevel=3)
    try:
        yield os.getcwd()
    finally:
        os.chdir(saved_dir)
        if is_temporary:
            rmtree(name) 
Example 44
Project: pyblish-win   Author: pyblish   File: test_repr.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        longname = 'areallylongpackageandmodulenametotestreprtruncation'
        self.pkgname = os.path.join(longname)
        self.subpkgname = os.path.join(longname, longname)
        # Make the package and subpackage
        shutil.rmtree(self.pkgname, ignore_errors=True)
        os.mkdir(self.pkgname)
        touch(os.path.join(self.pkgname, '__init__'+os.extsep+'py'))
        shutil.rmtree(self.subpkgname, ignore_errors=True)
        os.mkdir(self.subpkgname)
        touch(os.path.join(self.subpkgname, '__init__'+os.extsep+'py'))
        # Remember where we are
        self.here = os.getcwd()
        sys.path.insert(0, self.here) 
Example 45
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_curdir(self):
        self.assertEqual(realpath('.'), os.getcwd())
        self.assertEqual(realpath('./.'), os.getcwd())
        self.assertEqual(realpath('/'.join(['.'] * 100)), os.getcwd()) 
Example 46
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_pardir(self):
        self.assertEqual(realpath('..'), dirname(os.getcwd()))
        self.assertEqual(realpath('../..'), dirname(dirname(os.getcwd())))
        self.assertEqual(realpath('/'.join(['..'] * 100)), '/') 
Example 47
Project: pyblish-win   Author: pyblish   File: test_tempfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_wanted_dirs(self):
        # _candidate_tempdir_list contains the expected directories

        # Make sure the interesting environment variables are all set.
        with support.EnvironmentVarGuard() as env:
            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname:
                    env[envname] = os.path.abspath(envname)

            cand = tempfile._candidate_tempdir_list()

            for envname in 'TMPDIR', 'TEMP', 'TMP':
                dirname = os.getenv(envname)
                if not dirname: raise ValueError
                self.assertIn(dirname, cand)

            try:
                dirname = os.getcwd()
            except (AttributeError, os.error):
                dirname = os.curdir

            self.assertIn(dirname, cand)

            # Not practical to try to verify the presence of OS-specific
            # paths in this list. 
Example 48
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.cwd = os.getcwd()
        basetempdir = tempfile.gettempdir()
        os.chdir(basetempdir)
        self.data = 'We are the knights who say Ni!'
        self.tempdir = tempfile.mkdtemp(dir=basetempdir)
        self.tempdir_name = os.path.basename(self.tempdir)
        temp = open(os.path.join(self.tempdir, 'test'), 'wb')
        temp.write(self.data)
        temp.close() 
Example 49
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):
        self.translated = os.getcwd()
        self.translated = os.path.join(self.translated, 'filename')
        self.handler = SocketlessRequestHandler() 
Example 50
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 51
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 52
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_archive_cwd(self):
        current_dir = os.getcwd()
        def _breaks(*args, **kw):
            raise RuntimeError()

        register_archive_format('xxx', _breaks, [], 'xxx file')
        try:
            try:
                make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
            except Exception:
                pass
            self.assertEqual(os.getcwd(), current_dir)
        finally:
            unregister_archive_format('xxx') 
Example 53
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_tarfile_in_curdir(self):
        # Issue #21280
        root_dir = self.mkdtemp()
        saved_dir = os.getcwd()
        try:
            os.chdir(root_dir)
            self.assertEqual(make_archive('test', 'tar'), 'test.tar')
            self.assertTrue(os.path.isfile('test.tar'))
        finally:
            os.chdir(saved_dir) 
Example 54
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 55
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 56
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 57
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 58
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 59
Project: pyblish-win   Author: pyblish   File: posixpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def abspath(path):
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, _unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)


# Return a canonical path (i.e. the absolute location of a file on the
# filesystem). 
Example 60
Project: pyblish-win   Author: pyblish   File: os2emxpath.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def abspath(path):
    """Return the absolute version of a path"""
    if not isabs(path):
        if isinstance(path, unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

# realpath is a no-op on systems without islink support 
Example 61
Project: pyblish-win   Author: pyblish   File: configHandler.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def GetUserCfgDir(self):
        """Return a filesystem directory for storing user config files.

        Creates it if required.
        """
        cfgDir = '.idlerc'
        userDir = os.path.expanduser('~')
        if userDir != '~': # expanduser() found user home dir
            if not os.path.exists(userDir):
                warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
                        userDir + ',\n but the path does not exist.')
                try:
                    print(warn, file=sys.stderr)
                except IOError:
                    pass
                userDir = '~'
        if userDir == "~": # still no path to home!
            # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
            userDir = os.getcwd()
        userDir = os.path.join(userDir, cfgDir)
        if not os.path.exists(userDir):
            try:
                os.mkdir(userDir)
            except (OSError, IOError):
                warn = ('\n Warning: unable to create user config directory\n' +
                        userDir + '\n Check path and permissions.\n Exiting!\n')
                print(warn, file=sys.stderr)
                raise SystemExit
        # TODO continue without userDIr instead of exit
        return userDir 
Example 62
Project: pyblish-win   Author: pyblish   File: FileList.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def canonize(self, filename):
        if not os.path.isabs(filename):
            try:
                pwd = os.getcwd()
            except os.error:
                pass
            else:
                filename = os.path.join(pwd, filename)
        return os.path.normpath(filename) 
Example 63
Project: pyblish-win   Author: pyblish   File: IOBinding.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def defaultfilename(self, mode="open"):
        if self.filename:
            return os.path.split(self.filename)
        elif self.dirname:
            return self.dirname, ""
        else:
            try:
                pwd = os.getcwd()
            except os.error:
                pwd = ""
            return pwd, "" 
Example 64
Project: laugh-track   Author: davidrs   File: main.py    Apache License 2.0 5 votes vote down vote up
def translate_path(self, path):
        print "path: " + path

        if path == "/laugh":
            audio.play_laugh()

        elif path == "/nick-on":
	    rf.on(4)
        elif path == "/nick-off":
	    rf.off(4)
        elif path == "/dave-on":
	    rf.on(3)
        elif path == "/dave-off":
	    rf.off(3)
        elif path == "/living-room-on":
	    rf.on(2)
        elif path == "/living-room-off":
	    rf.off(2)
        elif path == "/applause":
	    audio.play_applause()
        else:
            print "Unkown command: " + path


	    # default root -> cwd        
        #root = os.getcwd()
        #print root
	# TODO: if path starts with client do this at the top, else return empty 200.
        # return unchanged path to get any appropriate files.
        return path[1:] 
Example 65
Project: aospy   Author: spencerahill   File: versioneer.py    Apache License 2.0 5 votes vote down vote up
def get_root():
    """Get the project root directory.

    We require that all commands are run from the project root, i.e. the
    directory that contains setup.py, setup.cfg, and versioneer.py .
    """
    root = os.path.realpath(os.path.abspath(os.getcwd()))
    setup_py = os.path.join(root, "setup.py")
    versioneer_py = os.path.join(root, "versioneer.py")
    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
        # allow 'python path/to/setup.py COMMAND'
        root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
        setup_py = os.path.join(root, "setup.py")
        versioneer_py = os.path.join(root, "versioneer.py")
    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):
        err = ("Versioneer was unable to run the project root directory. "
               "Versioneer requires setup.py to be executed from "
               "its immediate directory (like 'python setup.py COMMAND'), "
               "or in a way that lets it use sys.argv[0] to find the root "
               "(like 'python path/to/setup.py COMMAND').")
        raise VersioneerBadRootError(err)
    try:
        # Certain runtime workflows (setup.py install/develop in a setuptools
        # tree) execute all dependencies in a single python process, so
        # "versioneer" may be imported multiple times, and python's shared
        # module-import table will cache the first one. So we can't use
        # os.path.dirname(__file__), as that will find whichever
        # versioneer.py was first imported, even in later projects.
        me = os.path.realpath(os.path.abspath(__file__))
        me_dir = os.path.normcase(os.path.splitext(me)[0])
        vsr_dir = os.path.normcase(os.path.splitext(versioneer_py)[0])
        if me_dir != vsr_dir:
            print("Warning: build in %s is using versioneer.py from %s"
                  % (os.path.dirname(me), versioneer_py))
    except NameError:
        pass
    return root 
Example 66
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def check_call(cmd, cwd = os.getcwd(), timeout = None, env = os.environ):
    proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = env, cwd = cwd)
    if timeout:
        timer = Timer(timeout, proc.kill)
        timer.start()
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise OSError(proc.returncode, "Subprocess returned error code") 
Example 67
Project: BASS   Author: Cisco-Talos   File: ida_service.py    GNU General Public License v2.0 5 votes vote down vote up
def check_call(cmd, cwd = os.getcwd(), timeout = None, env = os.environ):
    proc = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess.PIPE, env = env, cwd = cwd)
    if timeout:
        timer = Timer(timeout, proc.kill)
        timer.start()
    stdout, stderr = proc.communicate()
    if proc.returncode != 0:
        raise OSError(proc.returncode, "Subprocess returned error code") 
Example 68
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: config.py    Apache License 2.0 5 votes vote down vote up
def test_main_module_paths(self):
        # Test an app with '__main__' as the import name, uses cwd.
        from main_app import app
        here = os.path.abspath(os.getcwd())
        self.assert_equal(app.instance_path, os.path.join(here, 'instance'))
        if 'main_app' in sys.modules:
            del sys.modules['main_app'] 
Example 69
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def get_root_path(import_name):
    """Returns the path to a package or cwd if that cannot be found.  This
    returns the path of a package or the folder that contains a module.

    Not to be confused with the package path returned by :func:`find_package`.
    """
    # Module already imported and has a file attribute.  Use that first.
    mod = sys.modules.get(import_name)
    if mod is not None and hasattr(mod, '__file__'):
        return os.path.dirname(os.path.abspath(mod.__file__))

    # Next attempt: check the loader.
    loader = pkgutil.get_loader(import_name)

    # Loader does not exist or we're referring to an unloaded main module
    # or a main module without path (interactive sessions), go with the
    # current working directory.
    if loader is None or import_name == '__main__':
        return os.getcwd()

    # For .egg, zipimporter does not have get_filename until Python 2.7.
    # Some other loaders might exhibit the same behavior.
    if hasattr(loader, 'get_filename'):
        filepath = loader.get_filename(import_name)
    else:
        # Fall back to imports.
        __import__(import_name)
        filepath = sys.modules[import_name].__file__

    # filepath is import_name.py for a module, or __init__.py for a package.
    return os.path.dirname(os.path.abspath(filepath)) 
Example 70
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: config.py    Apache License 2.0 5 votes vote down vote up
def test_main_module_paths(self):
        # Test an app with '__main__' as the import name, uses cwd.
        from main_app import app
        here = os.path.abspath(os.getcwd())
        self.assert_equal(app.instance_path, os.path.join(here, 'instance'))
        if 'main_app' in sys.modules:
            del sys.modules['main_app'] 
Example 71
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 5 votes vote down vote up
def get_root_path(import_name):
    """Returns the path to a package or cwd if that cannot be found.  This
    returns the path of a package or the folder that contains a module.

    Not to be confused with the package path returned by :func:`find_package`.
    """
    # Module already imported and has a file attribute.  Use that first.
    mod = sys.modules.get(import_name)
    if mod is not None and hasattr(mod, '__file__'):
        return os.path.dirname(os.path.abspath(mod.__file__))

    # Next attempt: check the loader.
    loader = pkgutil.get_loader(import_name)

    # Loader does not exist or we're referring to an unloaded main module
    # or a main module without path (interactive sessions), go with the
    # current working directory.
    if loader is None or import_name == '__main__':
        return os.getcwd()

    # For .egg, zipimporter does not have get_filename until Python 2.7.
    # Some other loaders might exhibit the same behavior.
    if hasattr(loader, 'get_filename'):
        filepath = loader.get_filename(import_name)
    else:
        # Fall back to imports.
        __import__(import_name)
        filepath = sys.modules[import_name].__file__

    # filepath is import_name.py for a module, or __init__.py for a package.
    return os.path.dirname(os.path.abspath(filepath)) 
Example 72
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: testapp.py    Apache License 2.0 5 votes vote down vote up
def iter_sys_path():
    if os.name == 'posix':
        def strip(x):
            prefix = os.path.expanduser('~')
            if x.startswith(prefix):
                x = '~' + x[len(prefix):]
            return x
    else:
        strip = lambda x: x

    cwd = os.path.abspath(os.getcwd())
    for item in sys.path:
        path = os.path.join(cwd, item or os.path.curdir)
        yield strip(os.path.normpath(path)), \
              not os.path.isdir(path), path != item 
Example 73
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: testapp.py    Apache License 2.0 5 votes vote down vote up
def iter_sys_path():
    if os.name == 'posix':
        def strip(x):
            prefix = os.path.expanduser('~')
            if x.startswith(prefix):
                x = '~' + x[len(prefix):]
            return x
    else:
        strip = lambda x: x

    cwd = os.path.abspath(os.getcwd())
    for item in sys.path:
        path = os.path.join(cwd, item or os.path.curdir)
        yield strip(os.path.normpath(path)), \
              not os.path.isdir(path), path != item 
Example 74
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 75
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 76
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 77
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 78
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 79
Project: RelayBot2.0   Author: nukeop   File: user.py    GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, bot, groupsinst, client):
        logger.info("Creating a User instance")

        self.client = client
        self.client.set_credential_location(os.getcwd())

        self.friends = steam.client.builtins.friends.SteamFriendlist(
            self.client)

        #This is a dictionary of group chats the bot is currently in
        #The keys are steam ids of the groups, and the values are lists of
        #steam ids of users in these group chats
        #If there is a group chat id here, it means the bot is in the chat
        #(unless the ghost chat bug happens)
        self.chats = {}

        #This is a dictionary storing information about user permissions as
        #obtained after entering group chats. Keys are steam ids, values are
        #lists of tuples where the first element is a groupid, and the second
        #element is the permission flag.
        self.permissions = {}

        self.bot = bot

        self.client.on('error', self.handle_errors)
        self.client.on('auth_code_required', self.auth_code_prompt)
        self.client.on(EMsg.ClientFriendMsgIncoming, self.on_chat_message)
        self.client.on(EMsg.ClientAccountInfo, self.on_account_info)
        self.client.on(EMsg.ClientFriendsList, self.on_client_friends_list)
        self.client.on(EMsg.ClientAddFriendResponse, self.on_friend_added)
        self.client.on(EMsg.ClientChatInvite, self.on_chat_invite)
        self.client.on(EMsg.ClientChatMsg, self.on_group_chat_msg)
        self.client.on(EMsg.ClientChatMemberInfo, self.on_chat_member_info)
        self.client.on(EMsg.ClientChatEnter, self.on_chat_enter)

        self.groups = groupsinst

        if self.client.relogin_available:
            self.client.relogin()
        else:
            self.client.login(config["STEAM_USER"], config["STEAM_PWD"])

        msg = self.client.wait_event(EMsg.ClientAccountInfo)

        self.client.wait_event(EMsg.ClientFriendsList)
        logger.info("Logged in as %s", msg[0].body.persona_name)
        logger.info("SteamID: %s", repr(self.client.steam_id))

        for groupid in config["AUTOJOIN"]:
            logger.info("Autojoining group:"
            " {}({})".format(self.groups.get_name(groupid), groupid))
            self.join_chat(groupid) 
Example 80
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: helpers.py    Apache License 2.0 4 votes vote down vote up
def find_package(import_name):
    """Finds a package and returns the prefix (or None if the package is
    not installed) as well as the folder that contains the package or
    module as a tuple.  The package path returned is the module that would
    have to be added to the pythonpath in order to make it possible to
    import the module.  The prefix is the path below which a UNIX like
    folder structure exists (lib, share etc.).
    """
    root_mod_name = import_name.split('.')[0]
    loader = pkgutil.get_loader(root_mod_name)
    if loader is None or import_name == '__main__':
        # import name is not found, or interactive/main module
        package_path = os.getcwd()
    else:
        # For .egg, zipimporter does not have get_filename until Python 2.7.
        if hasattr(loader, 'get_filename'):
            filename = loader.get_filename(root_mod_name)
        elif hasattr(loader, 'archive'):
            # zipimporter's loader.archive points to the .egg or .zip
            # archive filename is dropped in call to dirname below.
            filename = loader.archive
        else:
            # At least one loader is missing both get_filename and archive:
            # Google App Engine's HardenedModulesHook
            #
            # Fall back to imports.
            __import__(import_name)
            filename = sys.modules[import_name].__file__
        package_path = os.path.abspath(os.path.dirname(filename))
        # package_path ends with __init__.py for a package
        if loader.is_package(root_mod_name):
            package_path = os.path.dirname(package_path)

    site_parent, site_folder = os.path.split(package_path)
    py_prefix = os.path.abspath(sys.prefix)
    if package_path.startswith(py_prefix):
        return py_prefix, package_path
    elif site_folder.lower() == 'site-packages':
        parent, folder = os.path.split(site_parent)
        # Windows like installations
        if folder.lower() == 'lib':
            base_dir = parent
        # UNIX like installations
        elif os.path.basename(parent).lower() == 'lib':
            base_dir = os.path.dirname(parent)
        else:
            base_dir = site_parent
        return base_dir, package_path
    return None, package_path