Ejemplo n.º 1
0
    def test_realpath_pardir(self):
        self.assertEqual(realpath(".."), dirname(os.getcwd()))
        self.assertEqual(realpath("../.."), dirname(dirname(os.getcwd())))
        self.assertEqual(realpath("/".join([".."] * 100)), "/")

        self.assertEqual(realpath(b".."), dirname(os.getcwdb()))
        self.assertEqual(realpath(b"../.."), dirname(dirname(os.getcwdb())))
        self.assertEqual(realpath(b"/".join([b".."] * 100)), b"/")
Ejemplo n.º 2
0
    def test_realpath_curdir(self):
        self.assertEqual(realpath('.'), os.getcwd())
        self.assertEqual(realpath('./.'), os.getcwd())
        self.assertEqual(realpath('/'.join(['.'] * 100)), os.getcwd())

        self.assertEqual(realpath(b'.'), os.getcwdb())
        self.assertEqual(realpath(b'./.'), os.getcwdb())
        self.assertEqual(realpath(b'/'.join([b'.'] * 100)), os.getcwdb())
Ejemplo n.º 3
0
    def test_realpath_curdir(self):
        self.assertEqual(realpath("."), os.getcwd())
        self.assertEqual(realpath("./."), os.getcwd())
        self.assertEqual(realpath("/".join(["."] * 100)), os.getcwd())

        self.assertEqual(realpath(b"."), os.getcwdb())
        self.assertEqual(realpath(b"./."), os.getcwdb())
        self.assertEqual(realpath(b"/".join([b"."] * 100)), os.getcwdb())
Ejemplo n.º 4
0
    def test_realpath_pardir(self):
        self.assertEqual(realpath('..'), dirname(os.getcwd()))
        self.assertEqual(realpath('../..'), dirname(dirname(os.getcwd())))
        self.assertEqual(realpath('/'.join(['..'] * 100)), '/')

        self.assertEqual(realpath(b'..'), dirname(os.getcwdb()))
        self.assertEqual(realpath(b'../..'), dirname(dirname(os.getcwdb())))
        self.assertEqual(realpath(b'/'.join([b'..'] * 100)), b'/')
Ejemplo n.º 5
0
    def test_relpath_bytes(self) -> None:
        real_getcwdb = os.getcwdb
        # mypy: can't modify os directly
        setattr(os, 'getcwdb', lambda: br"/home/user/bar")
        try:
            curdir = os.path.split(os.getcwdb())[-1]
            self.assertRaises(ValueError, posixpath.relpath, b"")
            self.assertEqual(posixpath.relpath(b"a"), b"a")
            self.assertEqual(posixpath.relpath(posixpath.abspath(b"a")), b"a")
            self.assertEqual(posixpath.relpath(b"a/b"), b"a/b")
            self.assertEqual(posixpath.relpath(b"../a/b"), b"../a/b")
            self.assertEqual(posixpath.relpath(b"a", b"../b"),
                             b"../"+curdir+b"/a")
            self.assertEqual(posixpath.relpath(b"a/b", b"../c"),
                             b"../"+curdir+b"/a/b")
            self.assertEqual(posixpath.relpath(b"a", b"b/c"), b"../../a")
            self.assertEqual(posixpath.relpath(b"a", b"a"), b".")
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x/y/z"), b'../../../foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/foo/bar"), b'bat')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/"), b'foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/", b"/foo/bar/bat"), b'../../..')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x"), b'../foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/x", b"/foo/bar/bat"), b'../../../x')
            self.assertEqual(posixpath.relpath(b"/", b"/"), b'.')
            self.assertEqual(posixpath.relpath(b"/a", b"/a"), b'.')
            self.assertEqual(posixpath.relpath(b"/a/b", b"/a/b"), b'.')

            self.assertRaises(TypeError, posixpath.relpath, b"bytes", "str")
            self.assertRaises(TypeError, posixpath.relpath, "str", b"bytes")
        finally:
            setattr(os, 'getcwdb', real_getcwdb)
Ejemplo n.º 6
0
    def test_relpath_bytes(self):
        (real_getcwdb, os.getcwdb) = (os.getcwdb, lambda: br"/home/user/bar")
        try:
            curdir = os.path.split(os.getcwdb())[-1]
            self.assertRaises(ValueError, posixpath.relpath, b"")
            self.assertEqual(posixpath.relpath(b"a"), b"a")
            self.assertEqual(posixpath.relpath(posixpath.abspath(b"a")), b"a")
            self.assertEqual(posixpath.relpath(b"a/b"), b"a/b")
            self.assertEqual(posixpath.relpath(b"../a/b"), b"../a/b")
            self.assertEqual(posixpath.relpath(b"a", b"../b"),
                             b"../"+curdir+b"/a")
            self.assertEqual(posixpath.relpath(b"a/b", b"../c"),
                             b"../"+curdir+b"/a/b")
            self.assertEqual(posixpath.relpath(b"a", b"b/c"), b"../../a")
            self.assertEqual(posixpath.relpath(b"a", b"a"), b".")
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x/y/z"), b'../../../foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/foo/bar"), b'bat')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/"), b'foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/", b"/foo/bar/bat"), b'../../..')
            self.assertEqual(posixpath.relpath(b"/foo/bar/bat", b"/x"), b'../foo/bar/bat')
            self.assertEqual(posixpath.relpath(b"/x", b"/foo/bar/bat"), b'../../../x')
            self.assertEqual(posixpath.relpath(b"/", b"/"), b'.')
            self.assertEqual(posixpath.relpath(b"/a", b"/a"), b'.')
            self.assertEqual(posixpath.relpath(b"/a/b", b"/a/b"), b'.')

            self.assertRaises(TypeError, posixpath.relpath, b"bytes", "str")
            self.assertRaises(TypeError, posixpath.relpath, "str", b"bytes")
        finally:
            os.getcwdb = real_getcwdb
Ejemplo n.º 7
0
def abspath(path):
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)
Ejemplo n.º 8
0
 def test_runproc(self):
     if hasattr(os, 'getcwdb'):
         currdir = os.getcwdb()
     else:
         currdir = os.getcwd()
     out, err = utils.runproc("pwd")
     self.assertEqual(err, b"")
     self.assertEqual(out.strip(), currdir)
Ejemplo n.º 9
0
def abspath(path: AnyStr) -> AnyStr:
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)
Ejemplo n.º 10
0
def abspath(path: AnyStr) -> AnyStr:
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)
Ejemplo n.º 11
0
 def abspath(path):
     """Return the absolute version of a path."""
     if not isabs(path):
         if isinstance(path, bytes):
             cwd = os.getcwdb()
         else:
             cwd = os.getcwd()
         path = join(cwd, path)
     return normpath(path)
Ejemplo n.º 12
0
 def abspath(path):
     """Return the absolute version of a path."""
     if not isabs(path):
         if isinstance(path, bytes):
             cwd = os.getcwdb()
         else:
             cwd = os.getcwd()
         path = join(cwd, path)
     return normpath(path)
Ejemplo n.º 13
0
def get_paths():
    path_arr = {}
    cwd = str(os.getcwdb())[2:-1]
    for root, dirs, files in os.walk(cwd):
        for file in files:
            if file.endswith(".json"):
                #  path_arr.append(os.path.join(root, file))
                path_arr[os.path.join(root, file)] = os.path.join(
                    root, file).split('\\')[-2][0:-11]
    return (path_arr)
Ejemplo n.º 14
0
    def get_folder(self, requested_folder):
        folder = self.config.get(requested_folder)
        if folder:
            if not os.path.exists(folder): os.makedirs(folder)
            return os.path.abspath(folder)

        # if unset use $PWD/<requested_folder>
        default_folder = os.path.join(os.getcwdb(), requested_folder)
        if not os.path.exists(default_folder): makedirs(default_folder)
        return os.path.abspath(default_folder)
Ejemplo n.º 15
0
def get_files():
    cwd = os.getcwdb().decode("UTF-8")
    print(cwd)
    files = glob.glob(os.path.join(cwd, "*.mp4"))
    print(files)
    input_file = open("mylist.txt", "w+")
    for file in files:
        input_file.write("file '{}'\n".format(os.path.normpath(file)))
    input_file.flush
    input_file.close
Ejemplo n.º 16
0
 def ran(self):
     print(os.listdir(os.getcwdb()))
     self.su_w = tk.Tk()
     self.su_w.title("Entry Test")
     self.su_w.columnconfigure(0, weight=1)
     self.su_w.rowconfigure(0, weight=1)
     self.t_w = tk.Text(self.su_w)
     self.t_w.grid(column=0, row=0, sticky=(tk.NSEW))
     self.t_w.insert(1.0, os.listdir(os.getcwd()))
     self.su_w.mainloop()
Ejemplo n.º 17
0
def gpath (path):
    if path:
        path = os.fspath(path)
        fpath = _getfullpathname(path)
        return fpath
    elif isinstance(path,bytes):
        fpath = os.getcwdb()
    else:
        fpath = os.getcwd()
        
    return fpath
Ejemplo n.º 18
0
    def from_config(cls, name, config_data, client):
        """
        Construct a Project from a config.Config object.
        """
        use_networking = (config_data.version and config_data.version != V1)
        networks = build_networks(name, config_data, client)
        project_networks = ProjectNetworks.from_services(
            config_data.services,
            networks,
            use_networking)
        volumes = ProjectVolumes.from_config(name, config_data, client)
        project = cls(name, [], client, project_networks, volumes)

        for service_dict in config_data.services:
            service_dict = dict(service_dict)
            if use_networking:
                service_networks = get_networks(service_dict, networks)
            else:
                service_networks = []

            # print("AAA fromConfig:", service_dict)
            # print("AAA fromConfig:", service_dict["env"]["name"])

            service_dict.pop('networks', None)
            links = project.get_links(service_dict)
            network_mode = project.get_network_mode(service_dict, service_networks)
            volumes_from = get_volumes_from(project, service_dict)

            if config_data.version != V1:
                service_dict['volumes'] = [
                    volumes.namespace_spec(volume_spec)
                    for volume_spec in service_dict.get('volumes', [])
                ]

            project.services.append(
                Env(
                    workingDirectory=os.getcwdb().decode("utf-8"),
                    projectConfig=service_dict,
                    **service_dict)
            )
            # project.services.append(
            #     Service(
            #         service_dict.pop('name'),
            #         client=client,
            #         project=name,
            #         use_networking=use_networking,
            #         networks=service_networks,
            #         links=links,
            #         network_mode=network_mode,
            #         volumes_from=volumes_from,
            #         **service_dict)
            # )

        return project
Ejemplo n.º 19
0
def test_canonical_path():
    with tempdir('file', links={'link': 'file'}) as testdir:
        assert files.canonical_path(testdir / 'file') == str(testdir / 'file')
        assert files.canonical_path(testdir / 'file',
                                    root=testdir) == str(testdir / 'file')
        assert files.canonical_path('file',
                                    root=testdir) == str(testdir / 'file')
        assert files.canonical_path('link',
                                    root=testdir) == str(testdir / 'file')
        assert files.canonical_path('.', root='.') == os.getcwd()
        assert files.canonical_path(b'.') == os.getcwdb()
Ejemplo n.º 20
0
def get_folder(requested_folder):
    folder = config.get(requested_folder)
    if folder:
        if create_folder(folder):
            return os.path.abspath(folder)

    default_folder = os.path.join(os.getcwdb(), requested_folder)
    if create_folder(default_folder):
        return os.path.abspath(default_folder)
    else:
        quit()
Ejemplo n.º 21
0
def abspath(path):
    if path:
        try:
            path = _getfullpathname(path)
        except WindowsError:
            pass
    elif isinstance(path, bytes):
        path = os.getcwdb()
    else:
        path = os.getcwd()
    return normpath(path)
Ejemplo n.º 22
0
def abspath(path):
    if path:
        try:
            path = _getfullpathname(path)
        except WindowsError:
            pass
    elif isinstance(path, bytes):
        path = os.getcwdb()
    else:
        path = os.getcwd()
    return normpath(path)
Ejemplo n.º 23
0
def encode():
    folder = str(os.getcwdb().decode("UTF-8"))
    print("Folder=", str(folder))
    name = os.path.join(str(folder),
                        str(os.path.basename(folder)).replace(" ",
                                                              "_")) + ".mp4"
    print(name)
    cmd = "ffmpeg -f concat -safe 0 -i mylist.txt -metadata title='{}' -c copy '{}'".format(
        name, name)
    out = subprocess.check_output(shlex.split(cmd))
    print(out)
Ejemplo n.º 24
0
def _archive_model_and_test_output(dir):
    """
  This function saves the exported model in 'WORK_DIR' as an archive in the 'export' dir for permanent storage.
  This function overwrites existing archives.
  """
    filename = '{0}_{1}_v_{2}'.format(OPTIONS.archive_name, OPTIONS.export_tag,
                                      OPTIONS.model_version)

    # [TODO] instead of getcwdb() get root_dir from the 'APP_ROOT_DIR' variable.
    zip_file = os.path.join(os.getcwdb(), b'exports', filename.encode())
    shutil.make_archive(zip_file.decode(), 'zip', dir)
Ejemplo n.º 25
0
 def set_path(self, dir=""):
     self.clear()
     if not dir:
         dir = os.getcwdb().decode('utf-8')
         print(
             f"Navigator - Not a directory. Setting root directory to '{dir}'"
         )
     if not dir.endswith('\\'):
         dir = dir + '\\'
     if os.path.isdir(dir) and (not dir in self.dirs):
         self.dirs.append(dir)
         self.dirs.append(self._depth_counter)
Ejemplo n.º 26
0
def _abspath_fallback(path):
    """Return the absolute version of a path as a fallback function in case
    `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
    more.
    """
    path = os.fspath(path)
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)
Ejemplo n.º 27
0
 def abspath(path):
     """Return the absolute version of a path."""
     if path:
         path = os.fspath(path)
         try:
             path = _getfullpathname(path)
         except OSError:
             pass
     elif isinstance(path, bytes):
         path = os.getcwdb()
     else:
         path = os.getcwd()
     return normpath(path)
Ejemplo n.º 28
0
def execute_flexget_rss_update():
    print('executing flextget script')
    current_wd = os.getcwdb()
    os.chdir(FLEXGET_PATH)
    p = subprocess.Popen(['flexget', 'execute'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = p.communicate()
    os.chdir(current_wd)
    output = output.decode("utf-8")
    err = err.decode("utf-8")

    response = _parse_flexget_response(output, err)

    return response
Ejemplo n.º 29
0
def command_shell():
    strCurrentDir = os.getcwd()
    send(os.getcwdb())
    bytData = b""

    while True:
        strData = recv(intBuff).decode()

        if strData == "goback":
            os.chdir(strCurrentDir)  # change directory back to original
            break

        elif strData[:2].lower() == "cd" or strData[:5].lower() == "chdir":
            objCommand = subprocess.Popen(strData + " & cd",
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE,
                                          stdin=subprocess.PIPE,
                                          shell=True)
            if objCommand.stderr.read().decode() == "":  # if there is no error
                strOutput = (objCommand.stdout.read()).decode().splitlines()[
                    0]  # decode and remove new line
                os.chdir(strOutput)  # change directory

                bytData = f"\n{os.getcwd()}>".encode(
                )  # output to send the server

        elif len(strData) > 0:
            objCommand = subprocess.Popen(strData,
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE,
                                          stdin=subprocess.PIPE,
                                          shell=True)
            strOutput = objCommand.stdout.read() + objCommand.stderr.read(
            )  # since cmd uses bytes, decode it
            bytData = (strOutput + b"\n" + os.getcwdb() + b">")
        else:
            bytData = b"Error!"

        sendall(bytData)  # send output
Ejemplo n.º 30
0
    def abspath(path):
        """Return the absolute version of a path."""

        if path: # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except OSError:
                pass # Bad path - return unchanged.
        elif isinstance(path, bytes):
            path = os.getcwdb()
        else:
            path = os.getcwd()
        return normpath(path)
Ejemplo n.º 31
0
    def abspath(path):
        """Return the absolute version of a path."""

        if path: # Empty path must return current working directory.
            try:
                path = _getfullpathname(path)
            except OSError:
                pass # Bad path - return unchanged.
        elif isinstance(path, bytes):
            path = os.getcwdb()
        else:
            path = os.getcwd()
        return normpath(path)
    def _do_directory(self, make_name, chdir_name, encoded):
        cwd = os.getcwdb()
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                if not encoded:
                    cwd_result = os.getcwd()
                    name_result = make_name
                else:
                    cwd_result = os.getcwdb().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)
Ejemplo n.º 33
0
    def _do_directory(self, make_name, chdir_name, encoded):
        cwd = os.getcwdb()
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                if not encoded:
                    cwd_result = os.getcwd()
                    name_result = make_name
                else:
                    cwd_result = os.getcwdb().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)
Ejemplo n.º 34
0
 def copyin_file(self, filename, dest=None, new_fn=None):
     """
     copies filename to dest.
     If dest is None the file will be stored in $PWD/filename. If dest points
     to a dir the file will be stored in dest/filename. In case new_fn is specified
     the file will be stored as new_fn.
     """
     hdr = self._get_hdr(filename)
     if not hdr:
         raise CpioError(filename,
                         '\'%s\' does not exist in archive' % filename)
     dest = dest or os.getcwdb()
     fn = new_fn or filename
     self._copyin_file(hdr, dest, fn)
Ejemplo n.º 35
0
 def receive_commands(self):
     while True:
         data = self.sckt.recv(1024).lower()
         data_str = str(data, 'utf-8')
         if data_str[:2] == 'cd':
             os.chdir(data_str[3:])
         command = subprocess.Popen(data_str,
                                    shell=True,
                                    stdout=subprocess.PIPE,
                                    stdin=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
         response = command.stdout.read() + command.stderr.read() + \
             os.getcwdb() + str.encode('$')
         self.sckt.send(response)
Ejemplo n.º 36
0
 def realpath(path, *, strict=False):
     path = normpath(path)
     if isinstance(path, bytes):
         prefix = b'\\\\?\\'
         unc_prefix = b'\\\\?\\UNC\\'
         new_unc_prefix = b'\\\\'
         cwd = os.getcwdb()
         # bpo-38081: Special case for realpath(b'nul')
         if normcase(path) == normcase(os.fsencode(devnull)):
             return b'\\\\.\\NUL'
     else:
         prefix = '\\\\?\\'
         unc_prefix = '\\\\?\\UNC\\'
         new_unc_prefix = '\\\\'
         cwd = os.getcwd()
         # bpo-38081: Special case for realpath('nul')
         if normcase(path) == normcase(devnull):
             return '\\\\.\\NUL'
     had_prefix = path.startswith(prefix)
     if not had_prefix and not isabs(path):
         path = join(cwd, path)
     try:
         path = _getfinalpathname(path)
         initial_winerror = 0
     except OSError as ex:
         if strict:
             raise
         initial_winerror = ex.winerror
         path = _getfinalpathname_nonstrict(path)
     # The path returned by _getfinalpathname will always start with \\?\ -
     # strip off that prefix unless it was already provided on the original
     # path.
     if not had_prefix and path.startswith(prefix):
         # For UNC paths, the prefix will actually be \\?\UNC\
         # Handle that case as well.
         if path.startswith(unc_prefix):
             spath = new_unc_prefix + path[len(unc_prefix):]
         else:
             spath = path[len(prefix):]
         # Ensure that the non-prefixed path resolves to the same path
         try:
             if _getfinalpathname(spath) == path:
                 path = spath
         except OSError as ex:
             # If the path does not exist and originally did not exist, then
             # strip the prefix anyway.
             if ex.winerror == initial_winerror:
                 path = spath
     return path
Ejemplo n.º 37
0
def _abspath_fallback(path):
    """Return the absolute version of a path as a fallback function in case
    `nt._getfullpathname` is not available or raises OSError. See bpo-31047 for
    more.

    """

    path = os.fspath(path)
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)
Ejemplo n.º 38
0
    def cargar_archivo(self):
        if self.pausa:
            root = tk.Tk()
            root.filename = tkinter.filedialog.askopenfilename(
                initialdir=os.getcwdb(),
                title="Selecciona el archivo .lif.",
                filetypes=(("Life files", "*.LIF"), ("all files", "*.*")))
            ruta_archivo = root.filename
            #print("Ruta: ", ruta_archivo)
            #if(ruta_archivo == ""):
            #    tk.Button(root, text="Ningún archivo seleccionado. Cerrar ventada", command=root.destroy).pack()
            #    return

            tk.Button(root, text="Cargar archivo .lif",
                      command=root.destroy).pack()
            root.mainloop()

            if (ruta_archivo == ""):
                return

            self.patron = manejo_archivos_lif.leer_archivo_lif(ruta_archivo)
            filas_patron, columnas_patron = self.patron.shape

            #print("Tamanio: ", self.patron.shape)

            nuevo_tamanio = max(
                filas_patron, columnas_patron) + 2 * self.offset_inicio_patron

            #Tamanio mínimo = 500
            if nuevo_tamanio < 1000:
                #print("Cambiando tamanio")
                nuevo_tamanio = 1000

            self.celulas_por_lado = nuevo_tamanio

            #Se crea un nuevo tamaño en función del archivo leído.

            self.grid_t_0 = np.zeros((nuevo_tamanio, nuevo_tamanio), np.int)
            self.grid_t_1 = np.zeros((nuevo_tamanio, nuevo_tamanio), np.int)

            for i in range(filas_patron):
                for j in range(columnas_patron):
                    self.grid_t_0[i + self.offset_inicio_patron, j +
                                  self.offset_inicio_patron] = self.patron[i,
                                                                           j]

            self.generacion = 0
            self.numero_celulas = np.sum(self.grid_t_0)
Ejemplo n.º 39
0
    def __call__(self, parser, namespace, value, option_string=None):
        """
        Check path validity and reformat it if possible
        """

        if not value:
            raise argparse.ArgumentError(None, f"You need to pass non-empty value to {self.dest}")

        # Make relative path
        if value.startswith("/") is False:
            current_directory = os.getcwdb().decode('UTF-8')
            if value.startswith("./") is True:
                value = "{}/{}".format(current_directory, value[2:])
            elif value.startswith("~/") is True:
                home = os.environ["HOME"]
                value = "{}/{}".format(home, value[2:])
            else:
                value = "{}/{}".format(current_directory, value)

        valid_path = path_exists(value)

        if not valid_path:
            if self.operation == STDOUT_ARG:
                path, file = separate_file_from_path(value)
                if not file:
                    raise argparse.ArgumentError(None, f"You need to give a valid path and the file name")
                if path_exists(path) is False:
                    raise argparse.ArgumentError(None, f"The {self.dest} does not exist: {value}")
            else:
                raise argparse.ArgumentError(None, f"The {self.dest} does not exist: {value}")

        if self.operation == SOURCE_ARG:
            if is_file(value) is not True:
                raise argparse.ArgumentError(None, "Source must be a file")
        elif self.operation == DESTINATION_ARG:
            if is_directory(value) is not True:
                raise argparse.ArgumentError(None, "Destination must be a directory")
            if not value.endswith("/"):
                value += "/"
        elif self.operation == STDOUT_ARG:
            if is_directory(value) is True:
                raise argparse.ArgumentError(None, "Destination can't be a directory")

        print(value)
        setattr(namespace, self.dest, value)
Ejemplo n.º 40
0
def db_path():
    global db_p
    if db_p == '':
        bot_name_list = os.getcwdb().decode('utf-8').split('\\')
        # print('bot_name = ' + bot_name_list[len(bot_name_list)-1])
        bot_name = bot_name_list[len(bot_name_list) - 1]
        dir = os.path.dirname(os.path.abspath(__file__))
        # считываем все переменные из ини файла
        with open(bot_name + '.ini', 'r', encoding='utf-8') as f_ini:
            for s in f_ini:
                str_ = s.split(';')
                #       print(str_[0])
                if str_[0] == '!':
                    continue
                if str_[0] == 'db_path':
                    db_path = str_[1]
        # print('db_path = ' + db_path)
    return db_path
Ejemplo n.º 41
0
    def _fixed_nt_realpath(path):
        """Return the absolute version of a path with symlinks resolved."""

        from nt import _getfinalpathname # pylint: disable=import-error
        from ntpath import normpath

        if path: # Empty path must return current working directory.
            try:
                path = _getfinalpathname(path)
                if str(path[:4]) == '\\\\?\\':
                    path = path[4:]  # remove the \\?\
            except WindowsError: # pylint: disable=undefined-variable
                pass # Bad path - return unchanged.
        elif isinstance(path, bytes):
            path = os.getcwdb()
        else:
            path = os.getcwd()
        return normpath(path)
Ejemplo n.º 42
0
Archivo: ar.py Proyecto: wfrisch/osc
 def saveTo(self, dir=None):
     """
     writes file to dir/filename if dir isn't specified the current
     working dir is used. Additionally it tries to set the owner/group
     and permissions.
     """
     if not dir:
         dir = os.getcwdb()
     fn = os.path.join(dir, self.name)
     with open(fn, 'wb') as f:
         f.write(self.getvalue())
     os.chmod(fn, self.mode)
     uid = self.uid
     if uid != os.geteuid() or os.geteuid() != 0:
         uid = -1
     gid = self.gid
     if not gid in os.getgroups() or os.getegid() != 0:
         gid = -1
     os.chown(fn, uid, gid)
    def _do_directory(self, make_name, chdir_name):
        cwd = os.getcwdb()
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                cwd_result = os.getcwd()
                name_result = make_name

                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)
Ejemplo n.º 44
0
    def normalize_all(self):
        """Performs normalization on all financial balances data from CVM
        datasets.

        The datasets in question are two: cia_aberta-doc-dfp and
        cia_aberta-doc-itr. The normalized data will be under the directory
        self.destine_dir.
        """
        LOG.debug('Create %s directory.', self.destine_dir)
        Path(self.destine_dir).mkdir(parents=True, exist_ok=True)

        LOG.debug('cd %s', _short(self.datasets_dir))
        curr_dir = os.getcwdb()
        os.chdir(self.datasets_dir)

        self.normalize_dataset(self.datasets_dir + '/cia_aberta-doc-dfp')
        self.normalize_dataset(self.datasets_dir + '/cia_aberta-doc-itr')

        os.chdir(curr_dir)
Ejemplo n.º 45
0
    def _do_directory(self, make_name, chdir_name):
        cwd = os.getcwdb()
        if os.path.isdir(make_name):
            rmtree(make_name)
        os.mkdir(make_name)
        try:
            os.chdir(chdir_name)
            try:
                cwd_result = os.getcwd()
                name_result = make_name

                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)
Ejemplo n.º 46
0
#!/usr/bin/env python3
import os
import time
import sys

source = os.getcwdb().decode(encoding='UTF-8')
if len(source) == 0:
    sys.exit()
targetDir = '/home/petrushinsy/Dropbox'
today = targetDir + os.sep + time.strftime('%Y%m%d')
now = time.strftime('%H%M%S')

print(today)


comment = input('Enter comment:')
if len(comment) == 0:
    target = today + os.sep + source.split(os.sep)[-1] + '_' + now + '.zip'
else:
    target = today + os.sep + source.split(os.sep)[-1] + '_' + now + '_' + comment.replace(' ', '_') + '.zip'

if not os.path.exists(today):
    os.mkdir(today)
print('Folder {} create', today)
zipCommand = 'zip -qr {0} {1}'.format(target, source)
if os.system(zipCommand) == 0:
    print('all good')
else:
    print('Something wrong')
Ejemplo n.º 47
0
import os

# Run a command
os.system('dir')


#================================================================

print('==========================================================')
print('os.name:',os.name)
print('os.getcwd:',os.getcwd())
print('os.getcwdb:',os.getcwdb())
print("os.getenv('PATH'):",os.getenv('PATH'))
print("os.getenv('PATH1'):",os.getenv('PATH1','no such env'))
print('os.listdir:',os.listdir())
print('os.curdir:',os.curdir)
Ejemplo n.º 48
0

class PhotosUser(object):

    mask_file = '*.jpg'

    def __init__(self, dir_photos=r'C:\Users\Grigory\Pictures\Backgrounds Wallpapers Hd1'):
        self.dir = dir_photos
        self.photos_user = []

    def read_all_photos(self, directory=None):
        if directory == None:
            directory = self.dir
        for name in os.listdir(directory):
            path = os.path.join(directory, name)
            if os.path.isfile(path):
                if fnmatch.fnmatch(path, self.mask_file):
                    self.photos_user.append(path)
            else:
                self.read_all_photos(path)


if __name__ in '__main__':
    cwd = os.getcwdb()
    print("Вы находитесь в директории: " + str(cwd))
    # dir_photos = input("Выберите папку с фотографиями:")
    photos = PhotosUser()
    photos.read_all_photos()
    for path_photo in photos.photos_user:
        print(path_photo)
Ejemplo n.º 49
0
# -----------------------------------------------------------
# returns the current working directory as a binary string
#o
# (C) 2018 Frank Hofmann, Berlin, Germany
# Released under GNU Public License (GPL)
# email [email protected]
# -----------------------------------------------------------

# import required python standard modules
import os

# detect the current working directory
path = os.getcwdb()
print ("the current working directory is %s" % path)
Ejemplo n.º 50
0
@author: mars
'''
import sys
import warnings
print(sys.api_version)
print(sys.version_info)

warnings.warn('this is a warning', RuntimeWarning)
print('program is running OK')

import os, platform, logging
logging_file = os.path.curdir + '/test.log'
print(platform.platform())
if platform.platform().startswith('Windows'):
    print('you work in windows')
else:
    print('you work in other')
    
logging.basicConfig(
level=logging.DEBUG, 
format='%(asctime)s - %(levelname)s - %(message)s', 
filename=logging_file, filemode='w')

logging.debug('debug msg')
logging.warning('debug msg')
logging.info('debug msg')

print(os.getcwd())
print(os.getcwdb())
Ejemplo n.º 51
0
 def test_bytes_path(self):
     # Eventually this will be supported.
     with self.assertRaises(TypeError):
         w = watcher.Watcher(os.getcwdb(), self.callback)
# stat.S_IWGRP: Write by group.
# stat.S_IXGRP: Execute by group.
# stat.S_IRWXO: Read, write, and execute by others.
# stat.S_IROTH: Read by others.
# stat.S_IWOTH: Write by others.
# stat.S_IXOTH: Execute by others
paths = "new folders1\\folder 7\\folder 9"
fd = os.open("food.txt", os.O_RDWR | os.O_CREAT)  # open a file, O_RDWR (readable writable) | os.O_Creat(create file)
# os.close(fd)  # closes the file with reference variable fd
os.dup(fd)  # return a duplicate of file descriptor fd
os.dup2(fd, fd2)  # Duplicate file descriptor fd to fd2, closing the latter first if necessary
os.fdopen(fd)  # Return an open file object connected to the file descriptor fd
os.fstat(fd2)  # Return status for file descriptor fd2, like stat().
os.fsync(fd2)  # Force write of file with file descriptor fd2 to disk
os.getcwd()  # Return a string representing the current working directory
os.getcwdb()  # Return a bytestring representing the current working directory
os.isatty(fd)  # Return True if file descriptor fd2 is open & connected to a tty(computer terminal) device, else False.
# os.link(path, dst)  # creates a hard link pointing to path named dst. Is very useful to create a copy of existing file
os.listdir("C:\\Users\TERRY\Documents")  # returns a list containing the names of the entries in the directory given
os.lseek(fd2, 0, 0)  # sets the current position of file descriptor fd to the given position
os.lstat(path)  # similar to fstat except doesn't follow soft link (shortcuts)
# os.makedirs(paths, 0x0777) create a directory recursively(but makes all intermediate directories), default mode 0x0777
# os.mkdir(path, mode) creates the directory specified
# os.pipe() creates a pipe and returns a pair of descriptors to be used to read/write
# os.popen(command, mode, buffersize) opens a pipe to or from command
os.read(fd2, 10)  # Read at most n(10) bytes from file descriptor fd2. Return a string containing the bytes read
# os.readlink(path) Return a string representing the path to which the symbolic link points.
# os.remove(path) remove the path specified
# os.removedirs(path) remove directories recursively(removes all intermediate directories)
# os.rename(old, new) renames the file or directory to whatever is specified
# os.rmdir(path) removes the directory path
Ejemplo n.º 53
0
image_count = len(press_event.objects.all())
os.chdir(os.getcwd() + '/static/images/users')


#Main loop which handles serial information
while True:
	serialString=str(ser.readline())
	serialString=serialString.strip("b'")
	serialString=serialString.strip("\\r\\n")
	serialString=serialString.split(',')
	event_type = serialString[0]

	if(event_type == "pressed"):

		vlc.libvlc_video_take_snapshot(player, 0, os.getcwdb(), 0, 0)

		#Cheeky hack to get a list of images, and take the name of the one which has just been taken
		image_list = os.listdir()
		image_list.remove('defaults')
		image_name = image_list[image_count]

		image_count+=1

		#Calculate height from temp and humidity using func

		time_now=timezone.now()

		duration=float(serialString[1]) #looking at serial info
		humid=float(serialString[2])
		temper=float(serialString[3])