def test_os(self): self.assertEqual("posix", os.name) self.assertTrue( os.access(os.environ["HOME"], os.R_OK | os.W_OK | os.X_OK)) self.assertTrue(os.get_exec_path()) for name in os.get_exec_path(): with self.subTest(name=name): self.assertTrue(os.access(name, os.X_OK))
def __create_wallpaper_bash(): # Create and save the run.sh that will execute the AppleScript if the correct run.sh doesn't already exist. content = "#!/bin/bash\n" + "osascript " + os.get_exec_path( )[0] + "/./Scripts/wallpaper.scpt" if open(os.get_exec_path()[0] + "/./Scripts/run.sh", 'r').read() == content: return file = open(os.get_exec_path()[0] + "/./Scripts/run.sh", 'wb') file.write(bytes(content, 'UTF-8')) file.close()
def maybe_execute(fileinfo, execute=False, urllist=None): def _really_execute(cmd, shell=False, cwd=None): try: subprocess.Popen(cmd, shell=shell, cwd=cwd, env=os.environ) return True except OSError: return False if execute: fileinfo.refresh() filepath = fileinfo.absoluteFilePath() if fileinfo.isExecutable(): mimetype = get_mime_type(filepath) if mimetype in G.EXECUTABLES: if execute: path = fileinfo.absolutePath() if path in os.get_exec_path(): path = os.getenv("HOME", path) return _really_execute([filepath], cwd=path) else: return True if filepath.endswith(".desktop"): if fileinfo.isExecutable() or fileinfo.ownerId() == 0: entry = DesktopEntry.DesktopEntry(filepath) tryex = entry.getTryExec() tryex = True if tryex == "" else which(tryex) if not execute: return entry elif tryex: xec = parse_exec_line(entry, urllist=urllist) path = entry.getPath() or os.getenv("HOME") return _really_execute(xec, shell=True, cwd=path) return False
def binpaths(include_base=False, only_missing=False): """Return a list of directory paths Params ------ * include_base (bool, default=False) - search in base_prefix and base_exec_prefix for bin dirs too * only_missing (bool, default=False) - only include dirs missing from PATH """ prefixes = {sys.prefix, sys.exec_prefix} if include_base: prefixes |= {sys.base_prefix, sys.base_exec_prefix} dirs = { Path(d, CFG.binname).resolve() for d in prefixes if Path(d, CFG.binname).is_dir() } if not dirs: print("No valid bin path found", file=sys.stderr) if only_missing: dirs = [d for d in dirs if d not in os.get_exec_path()] if not dirs: print("No bin paths missing from PATH", file=sys.stderr) return dirs
def find_gams_directory(): """ Returns GAMS installation directory or None if not found. On Windows systems, this function looks for `gams.location` in registry; on other systems the `PATH` environment variable is checked. Returns: a path to GAMS installation directory or None if not found. """ if sys.platform == "win32": try: with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "gams.location") as gams_location_key: gams_path, _ = winreg.QueryValueEx(gams_location_key, None) if not _windows_dlls_exist(gams_path): return None return gams_path except FileNotFoundError: return None executable_paths = os.get_exec_path() for path in executable_paths: if "gams" in path.casefold(): return path return None
def has_program(command): ''' Checks whether given program is installed on this computer. :param str command: Name of command :returns: Whether program is installed :rtype: bool ''' def is_exe(path): return os.path.isfile(path) and os.access(path, os.X_OK) # Check if `command` is a path to an executable if os.sep in command: if is_exe(os.path.expanduser(command)): logger.debug('Command “{}” found.'.format(command)) return True # Check if `command` is an executable on PATH else: for dir in os.get_exec_path(): if is_exe(os.path.join(dir, command)): logger.debug('Command “{}” found.'.format(command)) return True logger.debug('Command “{}” not found.'.format(command)) return False
def _find_rscript(): path_dirs = get_exec_path() for adir in path_dirs: path = join(adir, "Rscript") if exists(path): return path raise RuntimeError("Rscript executable was not found.")
def have_tool(name): for dn in os.get_exec_path(): if os.path.isfile(os.path.join(dn, name)): return True if os.path.isfile(os.path.join(dn, name + ".exe")): return True return False
def find_executable(name: typing.AnyStr) -> typing.AnyStr: for path in os.get_exec_path(): binary_path = os.path.join(path, name) if os.path.exists(binary_path): return binary_path return None
def is_in_path(program): ''' Check if a program is in the system ``PATH``. Checks if a given program is in the user's ``PATH`` or not. Args: program (str): The program to try to find in ``PATH``. Returns: bool: Is the program in ``PATH``? ''' if sys.version_info.major == 2: path = os.getenv('PATH') if os.name == 'nt': path = path.split(';') else: path = path.split(':') else: path = os.get_exec_path() for i in path: if os.path.isdir(i): if program in os.listdir(i): return True
def require_stormctl(): """Skip the execution of tests if stormctl is not in $PATH.""" for path in os.get_exec_path(): name = os.path.join(path, 'stormctl') if os.access(name, os.X_OK): return pytest.skip('stormctl not found')
def shim_paths_with_program_files(env=None): if not env: env = os.environ program_files = env.get('PROGRAMFILES', '') if not program_files: return env.get('PATH', '') paths = [] try: for dirname in os.listdir(program_files): if dirname.lower() == 'tesseract-ocr': paths.append(os.path.join(program_files, dirname)) elif dirname.lower() == 'gs': try: latest_gs = max( os.listdir(os.path.join(program_files, dirname)), key=lambda d: float(d[2:]), ) except (FileNotFoundError, NotADirectoryError): continue paths.append( os.path.join(program_files, dirname, latest_gs, 'bin')) except EnvironmentError: pass paths.extend(path for path in os.get_exec_path(env) if path not in set(paths)) return os.pathsep.join(paths)
def _discover_modules_system() -> List["Module"]: """Find all aw- modules in PATH""" search_paths = os.get_exec_path() # Needed because PyInstaller adds the executable dir to the PATH if _parent_dir in search_paths: search_paths.remove(_parent_dir) logger.debug( "Searching for system modules in PATH: {}".format(search_paths)) modules: List["Module"] = [] paths = [p for p in search_paths if os.path.isdir(p)] for path in paths: try: ls = os.listdir(path) except PermissionError: logger.warning(f"PermissionError while listing {path}, skipping") continue for basename in ls: if not basename.startswith("aw-"): continue if not is_executable(os.path.join(path, basename), basename): continue name = _filename_to_name(basename) # Only pick the first match (to respect PATH priority) if name not in [m.name for m in modules]: modules.append(Module(name, Path(path) / basename, "system")) logger.info("Found system modules:") _log_modules(modules) return modules
def Create_Dir(self, dir_name): if not os.path.exists("data"): try: os.mkdir("data") print("Created directory 'data'") except: print("Unable to create directory 'data': Directory already exists") else: print("Unable to create directory 'data': Directory already exists") if not os.path.exists("data/data_" + dir_name): try: os.mkdir("data/data_" + dir_name) print("Created directory 'data/data_" + dir_name + "'") except: print("Unable to create directory 'data/data_" + dir_name + "': Directory already exists") else: print("Unable to create directory 'data/data_" + dir_name + "': Directory already exists") # Adding path. if not os.getcwd() in os.get_exec_path(): # print('adding path') if platform.system() == "Windows": os.environ["PATH"] = os.environ["PATH"] + ";" + os.getcwd() else: os.environ["PATH"] = os.environ["PATH"] + ":" + os.getcwd()
def get_exec_path(): PATH = [] OSPATH = os.get_exec_path() for k, dir_path in enumerate(OSPATH): if dir_path not in PATH[:k] and os.path.isdir(dir_path): PATH.append(dir_path) return PATH
def find_executable_in_path(self,env): ''' os.get_exec_path(env=None) Returns the list of directories that will be searched for a named executable, similar to a shell, when launching a process. env, when specified, should be an environment variable dictionary to lookup the PATH in. By default, when env is None, environ is used. ''' return os.get_exec_path(env=None)
def find_cdist_exec_in_path(): """Search cdist executable in os.get_exec_path() entries. """ for path in os.get_exec_path(): cdist_path = os.path.join(path, 'cdist') if os.access(cdist_path, os.X_OK): return cdist_path return None
def locate_path(program: str) -> List[str]: if os.path.isabs(program): return [program] for d in os.get_exec_path(): f = os.path.join(d, program) if os.access(f, os.X_OK): return [f] raise ValueError("%s not found on $PATH" % program)
def find_program(name, *, extra_paths=[]): """Return the path to a program.""" for path in [*extra_paths, *os.get_exec_path()]: exe = pathlib.Path(path, name) if os.access(exe, os.X_OK): return exe die('could not find program:', repr(name)) raise SystemExit(1)
def get_first_buffer(self) -> None: """ This method add some banner informations. """ path_exec = "\n\t".join(get_exec_path()) self.buffer = ( f"OS utilisé : {os.name}\nNombre de CPU : {cpu_count()}\n" f"Chemin d'exécution : \n\t{path_exec}")
def gradleCommand(self): gradlew = self._project.path('gradlew') if gradlew is None: for path in os.get_exec_path(): command = os.path.join(path, 'gradle') if os.access(command, os.X_OK): return command else: return gradlew
class Browser(): chromedriverPath = os.path.join(os.get_exec_path()[0], "..\\..\\helpers\\chromedriver.exe") driver = webdriver.Chrome(executable_path=chromedriverPath) wait = WebDriverWait(driver, 10) driver.maximize_window() def quit(context): context.driver.quit()
def get_banner(self): """ This method add some banner informations. """ path_exec = "\n\t".join(get_exec_path()) self.push( f"OS name : {os.name}\nThe number of processor : {cpu_count()}" f"Execution path : \n\t{path_exec}".encode())
def main() -> None: """Main function.""" parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument('--params', type=pathlib.Path, required=True) parser.add_argument('--pylintrc', type=pathlib.Path, required=True) parser.add_argument('--pytype', action='store_true', default=False) args = parser.parse_args() # Set a fake PYTHONPATH so that Pylint and Pytype can find imports for the # main and external workspaces. workspace = Workspace(args.params) # Pytype wants a Python binary available under the name “python”. See the # function pytype.tools.environment.check_python_exe_or_die. bindir = workspace.tempdir / 'bin' bindir.mkdir() (bindir / 'python').symlink_to(sys.executable) cwd = workspace.tempdir / 'phst_rules_elisp' env = dict(os.environ, PATH=os.pathsep.join([str(bindir)] + os.get_exec_path()), PYTHONPATH=os.pathsep.join(sys.path + workspace.path)) result = subprocess.run( [ sys.executable, '-m', 'pylint', # We’d like to add “--” after the options, but that’s not possible due # to https://github.com/PyCQA/pylint/issues/7003. '--persistent=no', '--rcfile=' + str(args.pylintrc.resolve()) ] + [str(file.relative_to(cwd)) for file in sorted(workspace.srcs)], check=False, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8', errors='backslashreplace') if result.returncode: print(result.stdout) sys.exit(result.returncode) if os.name == 'posix' and args.pytype: result = subprocess.run( [sys.executable, '-m', 'pytype', '--no-cache', '--'] + [str(file.relative_to(cwd)) for file in sorted(workspace.srcs)], check=False, cwd=cwd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='utf-8', errors='backslashreplace') if result.returncode: print(result.stdout) sys.exit(result.returncode) # Only clean up the workspace if we exited successfully, to help with # debugging. workspace.success()
def reset_search_path( self, default_path: Iterable[PathLike] = os.get_exec_path()) -> None: """Reset the search path to `default_path`. Args: default_path: The default executable path. """ self.search_path = () if default_path: self.add_search_path(default_path)
def __get_python2_interpreter(self): paths = os.get_exec_path() for p in paths: for prog in ["python2", "python2.exe"]: attempt = os.path.join(p, prog) if os.path.isfile(attempt): return attempt return ""
def search_path(program): path = None entries = os.get_exec_path() for entry in entries: if os.path.exists(os.path.join(entry, program)): path = entry break return path
def external_subcmds(): """this gets all files that are in $PATH and match mdt-* :returns dict with subcmd:full_path """ exec_paths = os.get_exec_path() mdt_executable_paths = [] for path in exec_paths: mdt_executable_paths += glob.glob(path + '/mdt-*') return exec_path_to_dict(mdt_executable_paths)
def which(program): fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: # for path in os.environ["PATH"].split(os.pathsep): for path in os.get_exec_path(): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def findPath( cmd ): allPath = os.get_exec_path( env = None ) for i in range( len(allPath) ): file = os.path.join(allPath[i], cmd) fileExists = os.path.isfile(file) if(fileExists): return file return False
def run(args, *, env=None, **kwargs): """Wrapper around subprocess.run() The main purpose of this wrapper is to allow us to substitute the main program for a spoof in the test suite. The hidden variable _OCRMYPDF_TEST_PATH replaces the main PATH as a location to check for programs to run. Secondly we have to account for behavioral differences in Windows in particular. Creating symbolic links in Windows requires administrator privileges and may not work if for some reason we're using a FAT file system or the temporary folder is on a different drive from the working folder. The test suite works around this by creating shim Python scripts that perform the same function as a symbolic link, but those shims require support on this side, to ensure we call them with Python. """ if not env: env = os.environ # Search in spoof path if necessary program = _get_program(args, env) # If we are running a .py on Windows, ensure we call it with this Python # (to support test suite shims) if os.name == 'nt' and program.lower().endswith('.py'): args = [sys.executable, program] + args[1:] else: args = [program] + args[1:] if os.name == 'nt': paths = os.pathsep.join(os.get_exec_path(env)) if not shutil.which(args[0], path=paths): shimmed_path = shim_paths_with_program_files(env) new_args0 = shutil.which(args[0], path=shimmed_path) if new_args0: args[0] = new_args0 process_log = log.getChild(os.path.basename(program)) process_log.debug("Running: %s", args) if sys.version_info < (3, 7) and os.name == 'nt': # Can't use close_fds=True on Windows with Python 3.6 or older # https://bugs.python.org/issue19575, etc. kwargs['close_fds'] = False proc = subprocess_run(args, env=env, **kwargs) if process_log.isEnabledFor(logging.DEBUG): try: stderr = proc.stderr.decode('utf-8', 'replace') except AttributeError: stderr = proc.stderr if stderr: process_log.debug("stderr = %s", stderr) return proc
def __init__(self, path_cls: Type[fs.Path]): self._implicit_abs_path_by_helper_path: Dict[fs.Path, fs.Path] = {} self._path_cls = path_cls self._successful_redo_run_count = 0 self._successful_nonredo_run_count = 0 # 1. check if the process' working directory is a working tree`s root self._root_path = _worktree.get_checked_root_path_from_cwd( os.getcwd(), path_cls) root_path = str(self._root_path.native) self._root_path_native_str = root_path # TODO make sure the "calling" source file is in the managed tree # path of all existing directories in os.get_exec_path(), that can be represented as dlb.fs.Path executable_search_paths = [] for p in os.get_exec_path(): # do _not_ expand a leading '~' try: pn = fs.Path.Native(p) if p and os.path.isdir(pn): p = fs.Path(pn, is_dir=True) if not p.is_absolute(): p = self._root_path / p if p not in executable_search_paths: executable_search_paths.append(p) except (OSError, ValueError): pass self._executable_search_paths = tuple(executable_search_paths) # 2. if yes: lock it _worktree.lock_working_tree(self._root_path) # 3. then prepare it self._temp_path_provider = None self._mtime_probe = None self._rundb = None try: if not isinstance(cf.max_dependency_age, datetime.timedelta): raise TypeError( "'dlb.cf.max_dependency_age' must be a datetime.timedelta object" ) if not cf.max_dependency_age > datetime.timedelta(0): raise ValueError( "'dlb.cf.max_dependency_age' must be positive") self._temp_path_provider, self._mtime_probe, self._rundb, self._is_working_tree_case_sensitive = \ _worktree.prepare_locked_working_tree(self._root_path, _rundb.SCHEMA_VERSION, cf.max_dependency_age) except BaseException: self._close_and_unlock_if_open() raise
def has_ffmpeg(self): """ffmpegがpathにあるか調べる""" for p in os.get_exec_path(): p = Path(p) w = p / "ffmpeg.exe" u = p / "ffmpeg" if w.is_file(): return True, "ffmpeg.exe" elif u.is_file(): return True, "ffmpeg" return False, ""
def which(executable: str) -> Path: """Looks in $PATH for `executable`. :param executable: name of executable to look up. :type executable: str :return: absolute path of executable. :rtype: pathlib.Path :raises ExecutableNotFoundException: if executable not found in path. """ for exec_path in os.get_exec_path(): path = Path(exec_path) / executable if path.exists(): return path.absolute() raise ExecutableNotFoundException(executable)
def find_tool(tool_name: str) -> str: '''Return a string describing how to invoke the given RISC-V tool Try to resolve the tool in the following way, stopping after the first match: 1. Use the path set in the RV32_TOOL_<tool_name> environment variable. 2. Use the path set in $TOOLCHAIN_PATH/bin/riscv32-unknown-elf-<tool_name>. 3. Look for riscv32-unknown-elf-<tool_name> in the system PATH. 4. Look in the default toolchain install location, /tools/riscv/bin. For methods (1) and (2), if the expected environment variable is set but the tool isn't found, an error is printed. An error is also printed if neither environment variables is set and methods (3) and (4) fail. ''' tool_env_var = 'RV32_TOOL_' + tool_name.upper() configured_tool_path = os.environ.get(tool_env_var) if configured_tool_path is not None: if not os.path.exists(configured_tool_path): raise RuntimeError('No such file: {!r} (derived from the ' '{!r} environment variable when trying ' 'to find the {!r} tool).'.format( configured_tool_path, tool_env_var, tool_name)) return configured_tool_path expanded = 'riscv32-unknown-elf-' + tool_name toolchain_path = os.environ.get('TOOLCHAIN_PATH') if toolchain_path is not None: tool_path = os.path.join(toolchain_path, 'bin', expanded) if not os.path.exists(tool_path): raise RuntimeError('No such file: {!r} (derived from the ' 'TOOLCHAIN_PATH environment variable when ' 'trying to find the {!r} tool).'.format( tool_path, tool_name)) return tool_path default_location = '/tools/riscv/bin' paths = os.get_exec_path() + [default_location] for exec_path in paths: tool_path = os.path.join(exec_path, expanded) if os.path.exists(tool_path): return tool_path raise RuntimeError('Unable to find {!r} in PATH or in {!r}. Set the {!r} ' 'or TOOLCHAIN_PATH environment variable if you ' 'installed your RISC-V toolchain in an alternate ' 'location.'.format(expanded, default_location, tool_env_var))
def run(): print('os.name', os.name) print('os.device_encoding(0)', os.device_encoding(0)) print('os.device_encoding(1)', os.device_encoding(1)) print('os.device_encoding(2)', os.device_encoding(2)) print('os.getcwd()', os.getcwd()) #~ print('os.getlogin()', os.getlogin()) print('os.getpid()', os.getpid()) print('os.getppid()', os.getppid()) print('os.get_exec_path()', os.get_exec_path()) print('os.supports_bytes_environ', os.supports_bytes_environ) print('os.times()', os.times()) width = max(len(x) for x in os.environ) for key in os.environ: print('{key:<{width}}= {}'.format(os.environ[key], **locals()))
def which(fileName): """Return the full path if the fileName is found somewhere in the PATH. If not found, return an empty string. Similar to the Linux which command. Arguments: fileName -- the name to search for """ extList = [''] if sys.platform.startswith('win'): extList.extend(os.getenv('PATHEXT', '').split(os.pathsep)) for path in os.get_exec_path(): for ext in extList: fullPath = os.path.join(path, fileName + ext) if os.access(fullPath, os.X_OK): return fullPath return ''
def test_get_exec_path(self): defpath_list = os.defpath.split(os.pathsep) test_path = ['/monty', '/python', '', '/flying/circus'] test_env = {'PATH': os.pathsep.join(test_path)} saved_environ = os.environ try: os.environ = dict(test_env) # Test that defaulting to os.environ works. self.assertSequenceEqual(test_path, os.get_exec_path()) self.assertSequenceEqual(test_path, os.get_exec_path(env=None)) finally: os.environ = saved_environ # No PATH environment variable self.assertSequenceEqual(defpath_list, os.get_exec_path({})) # Empty PATH environment variable self.assertSequenceEqual(('',), os.get_exec_path({'PATH':''})) # Supplied PATH environment variable self.assertSequenceEqual(test_path, os.get_exec_path(test_env)) if os.supports_bytes_environ: # env cannot contain 'PATH' and b'PATH' keys try: # ignore BytesWarning warning with warnings.catch_warnings(record=True): mixed_env = {'PATH': '1', b'PATH': b'2'} except BytesWarning: # mixed_env cannot be created with python -bb pass else: self.assertRaises(ValueError, os.get_exec_path, mixed_env) # bytes key and/or value self.assertSequenceEqual(os.get_exec_path({b'PATH': b'abc'}), ['abc']) self.assertSequenceEqual(os.get_exec_path({b'PATH': 'abc'}), ['abc']) self.assertSequenceEqual(os.get_exec_path({'PATH': b'abc'}), ['abc'])
def is_program_on_path(prog_name): """ Check if a program is found on the executable search path. Parameters: prog_name - String - Name of the program Returns: Boolean - True if program is found """ for path in os.get_exec_path(): if not path or not os.path.isdir(path): continue if prog_name in os.listdir(path): prog_path = os.path.join(path, prog_name) if os.access(prog_path, os.X_OK): return True return False
def populate(self): self.clear() G.populating = True G.abort = False directory = QtCore.QDir(self.menuAction().path()) directory.setSorting(self.root.sorting) directory.setFilter(self.root.filter) file_list = directory.entryInfoList() in_path = self.menuAction().path() in os.get_exec_path() try: G.App.installEventFilter(self) for i, item in enumerate(file_list): file_list[i] = MenuEntry(item, root=self.root, parent=self, in_path=in_path) self.addActions(file_list) except StopPopulating: self.die() return None finally: G.App.removeEventFilter(self) G.populating = False
def test_os(): cwd = os.getcwd() print('当前工作目录:', cwd) execpath = os.get_exec_path() print('exec_path:', execpath) login = os.getlogin() print('login name:', login) cur_dir = os.path.dirname(__file__) print('当前文件所在目录:', cur_dir) try: newdir = cur_dir + '\\test\\test' if os.path.isdir(newdir): os.rmdir(newdir) print(newdir + ' removed.') os.mkdir(newdir) print(newdir + ' created.') finally: pass
def is_in_path(filename): for d in os.get_exec_path(): if os.path.exists(os.path.join(d, filename)): return True return False
import sys import os from ..utils.exceptions import PleaseException def create_error_config(name): class ErrConfig: def __init__(self, source): raise PleaseException('no config found for language ' + name) ErrConfig.__name__ = name.title() + 'ErrConfig' return ErrConfig def is_windows(): return sys.platform.startswith('win') PATH = os.get_exec_path() if is_windows() or os.path.__name__ == 'ntpath': exe_suffix = '.exe' def run_command(name): return os.path.splitext(name)[0] + exe_suffix else: exe_suffix = '' def run_command(name): name = os.path.splitext(name)[0] if os.sep not in name: return os.path.join(os.curdir, name) return name def exists(name): if os.sep in name: variants = [name]
def install(): os.system('chmod +x bin/*') os.system('chmod +x install/*') os.system('chmod +x update/*') os.system('chmod +x main.py') os.system('chmod +x PampaMT.py') error_language = True while error_language: language = input('Set language (en_US/pt_BR): ') if language in ['en_US', 'pt_BR']: error_language = False print('Language = ' + language) print('') else: print('[Error] ...') print('') arq_dic_language = open(user + '/.PampaMT/file/set_language', 'w') arq_dic_language.write(language + '.dic') arq_dic_language.close() error_set_bash = True while error_set_bash: terminal = input('Do you want the terminal to open when you start PampaMT (Y/n)?: ') if terminal in ['Y', 'y', 'S', 's']: terminal_open = 'true' error_set_bash = False elif terminal in ['N', 'n']: terminal_open = 'false' error_set_bash = False else: print('Error ...') print('') arq_desktop = open(user + '/.local/share/applications/pampamt.desktop', 'w') arq_desktop.write('[Desktop Entry]\n' 'Version=0.1.0\n' 'Type=Application\n' 'Name=PampaMT\n' 'Exec="' + user + '/.PampaMT/bin/open_pampamt" %f\n' 'Icon=' + user + '/.PampaMT/image/logo3.png\n' 'Comment=App to Processing Magnetotelluric Data\n' 'Categories=Processing;MT;\n' 'Terminal=' + terminal_open +'\n' 'StartupNotify=true\n' 'StartupWMClass=pampamt\n') arq_desktop.close() if os.path.isdir(user + '/PampaMT'): pass else: os.mkdir(user + '/PampaMT') if os.path.isdir(user + '/PampaMT/PROC_MT'): pass else: os.mkdir(user + '/PampaMT/PROC_MT') if os.path.isdir(user + '/PampaMT/DADOS_MT'): pass else: os.mkdir(user + '/PampaMT/DADOS_MT') if os.path.isdir(user + '/modelo'): os.mkdir(user + '/PampaMT/modelo') os.system('cp -r ' + user + '/modelo ' + user + '/PampaMT/') os.chdir(user + '/PampaMT') elif os.path.isfile(user + '/modelo.tar.xz'): os.system('cp ' + user + '/modelo.tar.xz ' + user + '/PampaMT/modelo.tar.xf') os.chdir(user + '/PampaMT') os.system('tar xf modelo.tar.xf') os.system('rm modelo.tar.xf') else: print("Copy the file 'modelo.tar.xf' to " + user) print('Please contact Patrick Rogger Garcia to obtain the processing model (modelo.tar.xf)') print('E-mail: [email protected]') exit() list_dnff = [] for path in os.get_exec_path(): for dnff in glob.glob(path + '/*dnff*'): list_dnff.append(dnff) if len(list_dnff) == 0: print('Please install the EMTF package, visit:') print('http://mtnet.info/programs/egbert.html') exit() if os.path.isfile(user + '/bin/processamentoZ'): pass else: print('Please contact Patrick Rogger Garcia to obtain the processamentoZ') print('E-mail: [email protected]') exit() if os.path.isfile(user + '/bin/parametros-mt'): pass else: print('Please contact Patrick Rogger Garcia to obtain the parametros-mt') print('E-mail: [email protected]') exit() os.mkdir('modelo/PampaMT') os.mkdir('modelo/PampaMT/band_asc') os.mkdir('modelo/PampaMT/file_pplt') os.system('ln -s ~/.PampaMT/bin/pampamt.py ~/bin/pampamt') print('Finish install PampaMT') print('Update PampaMT, type: pampamt update') print('Remove PampaMT, type: pampamt remove') print('') print('Type: pampamt')
def find_coqtop(): for path in [os.path.join(entry, 'coqtop') for entry in os.get_exec_path()]: if os.access(path, os.X_OK): return path
def main(): parser = argparse.ArgumentParser(description='Use this script for import photo to Eburg') parser.add_argument("token", type=str, help="Access token for application") parser.add_argument("fromGroup", type=int, help="Идентификатор группы, из которой хотите импортировать фотографии") parser.add_argument("fromAlbum", type=int, help="Идентификатор(-ы) альбома(-ов), из которого(-ых) хотите импортировать фотографии") parser.add_argument("toGroup", type=int, # required=false, help="Идентификатор группы, в которую хотите экспортировать фотографии") parser.add_argument("toAlbum", type=int, # required=false, help="Идентификатор альбома, в который хотите экспортировать фотографии") args = parser.parse_args() my_app_id = '5117295' vkapi = vk.API(access_token=args.token) bal = vkapi.groups.search(q="Балы УрФУ", count=1)['items'][0] albumFrom = vkapi.photos.getAlbums(owner_id=args.fromGroup, album_ids=args.fromAlbum)['items'][0] print(albumFrom) albumTo = vkapi.photos.getAlbums(owner_id=args.toGroup, album_ids=args.toAlbum)['items'][0] print(albumTo) # # for photo in vkapi.photos.get(owner_id='-'+str(bal['id']), album_id=albumFrom['id'])['items']: # try: # time.sleep(1) # vkapi.photos.copy(owner_id='-'+str(bal['id']), photo_id=photo['id']) # print(photo) # except Exception as e: # print(e) for photo in vkapi.photos.get(owner_id=args.fromGroup, album_id=args.fromAlbum, photo_sizes=1)['items']: try: time.sleep(1) sizez = filter(lambda size: size['type'] == 'z', photo['sizes']) urllib.request.urlretrieve(sizez.__next__()['src'], str(photo['id'])+'.png') img = {'photo': (str(photo['id'])+'.png', open(str(photo['id'])+'.png', 'rb'))} urlpost = vkapi.photos.getUploadServer(group_id=-albumTo['owner_id'], album_id=albumTo['id'])['upload_url'] Resp = requests.post(urlpost, files=img) response = json.loads(Resp.text) vkapi.photos.save( group_id=response['gid'], server=response['server'], photos_list=response['photos_list'], album_id=response['aid'], hash=response['hash'] ) print(photo) except Exception as e: print(e) for photo in os.listdir(os.get_exec_path()): print(photo)
from .base import BaseConfig from .utils import is_windows import sys import itertools import logging import os import glob, fnmatch _logger = logging.getLogger('please_logger.lang_config.python2') LANGUAGE = "python2" exec_path = [os.path.normpath(p) for p in os.get_exec_path()] def _find_py2_install_win(): import winreg def _test_hkey(hkey): try: regkey = winreg.OpenKey(hkey, r'SOFTWARE\Python\Pythoncore') except WindowsError: return [] versions = [] for index in itertools.count(): try: keyname = winreg.EnumKey(regkey, index) except WindowsError: break else: if not keyname.startswith('2.'): continue with winreg.OpenKey(regkey, keyname) as verskey:
def _execute_child(self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, start_new_session): if isinstance(args, (str, bytes)): args = [args] else: args = list(args) if shell: args = ['/bin/sh', '-c'] + args if executable: args[0] = executable if executable is None: executable = args[0] orig_executable = executable (errpipe_read, errpipe_write) = _create_pipe() try: try: if env is not None: env_list = [os.fsencode(k) + b'=' + os.fsencode(v) for (k, v) in env.items()] else: env_list = None executable = os.fsencode(executable) if os.path.dirname(executable): executable_list = (executable,) else: executable_list = tuple(os.path.join(os.fsencode(dir), executable) for dir in os.get_exec_path(env)) fds_to_keep = set(pass_fds) fds_to_keep.add(errpipe_write) self.pid = _posixsubprocess.fork_exec(args, executable_list, close_fds, sorted(fds_to_keep), cwd, env_list, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, errpipe_read, errpipe_write, restore_signals, start_new_session, preexec_fn) self._child_created = True finally: os.close(errpipe_write) devnull_fd = getattr(self, '_devnull', None) if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd: os.close(p2cread) if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd: os.close(c2pwrite) if errwrite != -1 and errread != -1 and errwrite != devnull_fd: os.close(errwrite) if devnull_fd is not None: os.close(devnull_fd) self._closed_child_pipe_fds = True errpipe_data = bytearray() while True: part = _eintr_retry_call(os.read, errpipe_read, 50000) errpipe_data += part if not part or len(errpipe_data) > 50000: break finally: os.close(errpipe_read) if errpipe_data: try: _eintr_retry_call(os.waitpid, self.pid, 0) except OSError as e: while e.errno != errno.ECHILD: raise try: (exception_name, hex_errno, err_msg) = errpipe_data.split(b':', 2) except ValueError: exception_name = b'RuntimeError' hex_errno = b'0' err_msg = b'Bad exception data from child: ' + repr(errpipe_data) child_exception_type = getattr(builtins, exception_name.decode('ascii'), RuntimeError) err_msg = err_msg.decode(errors='surrogatepass') if issubclass(child_exception_type, OSError) and hex_errno: errno_num = int(hex_errno, 16) child_exec_never_called = err_msg == 'noexec' if child_exec_never_called: err_msg = '' if errno_num != 0: err_msg = os.strerror(errno_num) if errno_num == errno.ENOENT: if child_exec_never_called: err_msg += ': ' + repr(cwd) else: err_msg += ': ' + repr(orig_executable) raise child_exception_type(errno_num, err_msg) raise child_exception_type(err_msg)