我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.X_OK。
def which(program): """Determines whether program exists """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file raise
def main(argv): dir_ = argv[1] for entry in sorted(os.listdir(dir_)): path = os.path.join(dir_, entry) size = os.path.getsize(path) mtime = os.path.getmtime(path) mtime_format = time.strftime("%b %d %H:%M", time.localtime(mtime)) reset = '\033[0m' if os.path.isdir(path): color = '\033[1;94m' elif os.access(path, os.X_OK): color = '\033[1;92m' else: color = '' senf.print_("%6d %13s %s%s%s" % (size, mtime_format, color, entry, reset))
def check_exe(name, env=None): """ Ensure that a program exists :type name: string :param name: name or path to program :return: path of the program or None """ if not name: raise ValueError('Cannot execute an empty string!') def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(name) if fpath and is_exe(name): return os.path.abspath(name) else: env = env or os.environ for path in env["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, name) if is_exe(exe_file): return os.path.abspath(exe_file) return None
def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None #source: https://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file
def check_job_path(jobs_dir, job): if 'path' not in job: raise Exception('job does not have the "path" attribute: %s' % job) if not isinstance(job['path'], basestring): raise Exception('"path" attribute is not a string: %s' % job) # check that 'path' is rooted in the same directory as the .vcsjob file if job['path'].startswith('/'): raise Exception('job path is not relative: %s' % job['path']) path = os.path.normpath(os.path.join(jobs_dir, job['path'])) if not path.startswith(jobs_dir): raise Exception('job path is not inside the job tree: %s' % path) # also check that the job exists and is runnable if not os.path.isfile(path): raise Exception('no such file: %s' % path) if not os.access(path, os.X_OK): raise Exception('file is not executable: %s' % path) if 'profiles' not in job: job['profiles'] = None
def find_ancestor_cmd_path(self, cmd, cwd): """Recursively check for command binary in ancestors' node_modules/.bin directories.""" node_modules_bin = path.normpath(path.join(cwd, 'node_modules/.bin/')) binary = path.join(node_modules_bin, cmd) if sublime.platform() == 'windows' and path.splitext(binary)[1] != '.cmd': binary += '.cmd' if binary and access(binary, X_OK): return binary parent = path.normpath(path.join(cwd, '../')) if parent == '/' or parent == cwd: return None return self.find_ancestor_cmd_path(cmd, parent)
def which1(program, pathstr=None): if pathstr is None: pathstr = os.environ["PATH"] def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in pathstr.split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def is_executable_available(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath = os.path.dirname(program) if fpath: if is_exe(program): return True else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return True return False
def set_directory(self, directory): """Set the directory where the downloaded file will be placed. May raise OSError if the supplied directory path is not suitable. """ if not path.exists(directory): raise OSError(errno.ENOENT, "You see no directory there.", directory) if not path.isdir(directory): raise OSError(errno.ENOTDIR, "You cannot put a file into " "something which is not a directory.", directory) if not os.access(directory, os.X_OK | os.W_OK): raise OSError(errno.EACCES, "This directory is too hard to write in to.", directory) self.destDir = directory
def _popen(command, args): import os path = os.environ.get("PATH", os.defpath).split(os.pathsep) path.extend(('/sbin', '/usr/sbin')) for dir in path: executable = os.path.join(dir, command) if (os.path.exists(executable) and os.access(executable, os.F_OK | os.X_OK) and not os.path.isdir(executable)): break else: return None # LC_ALL to ensure English output, 2>/dev/null to prevent output on # stderr (Note: we don't have an example where the words we search for # are actually localized, but in theory some system could do so.) cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args) return os.popen(cmd)
def which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def _which(self, program): ''' Mimics which in the unix shell. ''' def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def _which(program): import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def _which(self, program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def _find_oc(): """ Determine the path to oc command Search /usr/bin:/usr/local/bin Returns: str: path to oc binary """ test_paths = ['/usr/bin/oc', '/usr/local/bin/oc'] for path in test_paths: test_path = utils.get_path(path) logger.debug("trying oc at " + test_path) oc = test_path if os.access(oc, os.X_OK): logger.debug("found oc at " + test_path) return oc logger.fatal("No oc found in {}. Please provide corrent path to co " "binary using --oc argument".format(":".join(test_paths))) return None
def _which(self, program): """Simple function to determine the path of an executable. Borrowed from https://github.com/amoffat/sh/blob/master/sh.py#L300. Thanks Andrew Moffat! sh is pretty awesome :^) """ def is_exe(fpath): return (os.path.exists(fpath) and os.access(fpath, os.X_OK) and os.path.isfile(os.path.realpath(fpath))) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: if "PATH" not in os.environ: return None for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def search_for(name): if name.startswith( '"' ): name = name.split('"')[1] else: name = name.split()[0] if win(): for i in get_env_var('PATH').split(';'): fname = os.path.join(i, name) if os.access(fname, os.X_OK) and not os.path.isdir(fname): return 1 if os.access(name, os.X_OK) and not os.path.isdir(name): return 1 else: for i in os.environ['PATH'].split(':'): #not win() fname = os.path.join(i, name) if os.access(fname, os.X_OK) and not os.path.isdir(fname): return 1 return 0
def getInterpreter(cmdline: "typing.Sequence[str]") -> "typing.Optional[typing.List[str]]": """ :param cmdline: The command to check :return: The interpreter command if the executable does not have execute permissions """ executable = Path(cmdline[0]) print(executable, os.access(str(executable), os.X_OK), cmdline) if not executable.exists(): executable = Path(shutil.which(str(executable))) statusUpdate(executable, "is not executable, looking for shebang:", end=" ") with executable.open("r", encoding="utf-8") as f: firstLine = f.readline() if firstLine.startswith("#!"): interpreter = shlex.split(firstLine[2:]) statusUpdate("Will run", executable, "using", interpreter) return interpreter else: statusUpdate("No shebang found.") return None
def which(program): """Locate `program` in PATH Arguments: program (str): Name of program, e.g. "python" """ def is_exe(fpath): if os.path.isfile(fpath) and os.access(fpath, os.X_OK): return True return False for path in os.environ["PATH"].split(os.pathsep): for ext in os.getenv("PATHEXT", "").split(os.pathsep): fname = program + ext.lower() abspath = os.path.join(path.strip('"'), fname) if is_exe(abspath): return abspath return None
def exe_exists(exe): """Determine whether path/name refers to an executable. :param str exe: Executable path or name :returns: If exe is a valid executable :rtype: bool """ def is_exe(path): """Determine if path is an exe.""" return os.path.isfile(path) and os.access(path, os.X_OK) path, _ = os.path.split(exe) if path: return is_exe(exe) else: for path in os.environ["PATH"].split(os.pathsep): if is_exe(os.path.join(path, exe)): return True return False
def is_binary_in_path(path, binary): """ Checks if the given binary is available in the specified path. Returns: True or False (Boolean) """ import os def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) path = path.strip('"') exe_file = os.path.join(path, binary) if is_exe(exe_file): return True return False
def run_all(self): # check that a compiled binary exists to run on the testcases argv = os.path.abspath(os.path.join(self.answer_dir, self.run_program)) if not (os.path.isfile(argv) and os.access(argv, os.X_OK)): logging.error("executable missing: {0}".format(argv)) print >>sys.stderr, "Compile your source file to create an executable {0}".format(argv) sys.exit(1) # check if testcases has subdirectories testcase_subdirs = iocollect.getdirs(os.path.abspath(self.testcase_dir)) if len(testcase_subdirs) > 0: for subdir in testcase_subdirs: files = iocollect.getfiles(os.path.abspath(os.path.join(self.testcase_dir, subdir))) self.run_path(subdir, files) else: files = iocollect.getfiles(os.path.abspath(self.testcase_dir)) self.run_path(None, files) return True
def run_all(self): # check that a compiled binary exists to run on the testcases argv = os.path.abspath(os.path.join(self.answer_dir, self.run_program)) if not (os.path.isfile(argv) and os.access(argv, os.X_OK)): logging.error("executable missing: {}".format(argv)) print >>sys.stderr, "Compile your source file to create an executable {}".format(argv) sys.exit(1) # check if testcases has subdirectories testcase_subdirs = iocollect.getdirs(os.path.abspath(self.testcase_dir)) if len(testcase_subdirs) > 0: for subdir in testcase_subdirs: files = iocollect.getfiles(os.path.abspath(os.path.join(self.testcase_dir, subdir))) self.run_path(subdir, files) else: files = iocollect.getfiles(os.path.abspath(self.testcase_dir)) self.run_path(None, files) return True
def which(program): """ Checks if executable exists and is on the path. Thanks http://stackoverflow.com/a/377028/119592 """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def which(program): """ Emulates the unix ``which`` command. Snatched from: `http://stackoverflow.com/questions/377017/ test-if-executable-exists-in-python` :param program: executable :type program: string :returns: path-to-executable or None """ def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def py_where(program, path=None): # From: http://stackoverflow.com/a/377028/548792 try: winprog_exts = tuple(p.upper() for p in os.environ['PATHEXT'].split(os.pathsep)) except: winprog_exts = is_win and ('.BAT', 'COM', '.EXE') or () def is_exec(fpath): return osp.isfile(fpath) and os.access(fpath, os.X_OK) and ( os.name != 'nt' or not winprog_exts or any(fpath.upper().endswith(ext) for ext in winprog_exts)) progs = [] if not path: path = os.environ["PATH"] for folder in path.split(os.pathsep): folder = folder.strip('"') if folder: exe_path = osp.join(folder, program) for f in [exe_path] + ['%s%s' % (exe_path, e) for e in winprog_exts]: if is_exec(f): progs.append(f) return progs
def which(program): def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def which(program): """ Check if a program/executable exists :param program: :return: """ def is_exe(f_path): return os.path.isfile(f_path) and os.access(f_path, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def which(program): """Determine full path of executable *program* on :envvar:`PATH`. (Jay at http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python) """ def is_exe(fpath): """ Returns True is the path points to an executable file. """ return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, _ = os.path.split(program) if fpath: real_program = realpath(program) if is_exe(real_program): return real_program else: for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None
def ensure_requirements(self): """Make sure kubectl and minikube are available.""" uname = run_result("uname").lower() for path, url in zip([MINIKUBE, KUBECTL], [ "https://storage.googleapis.com/minikube/releases/" "v0.15.0/minikube-{}-amd64", "https://storage.googleapis.com/kubernetes-release/" "release/v1.5.1/bin/{}/amd64/kubectl" ]): if path.exists() and not os.access(str(path), os.X_OK): # Apparently failed halfway through previous download os.remove(str(path)) if not path.exists(): self.echo("Downloading {}...".format(path.name)) check_call([ "curl", "--create-dirs", "--silent", "--output", str(path), url.format(uname) ]) path.chmod(0o755)