我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用errno.EPERM。
def terminate(self): try: os.kill(self.pid, signal.SIGTERM) except OSError, e: if e.errno == errno.ESRCH: return # process already killed by someone else if e.errno == errno.EPERM: # this can only happen if the original session was started as # a different user. e.g. if the broker has been restarted with # --demote=<some other user>. but don't worry too much about it # as sessions are eventually terminated anyway. print( 'WARNING: session with PID=%d not terminated because it ' 'is owned by a different user. did you restart a broker ' 'as a different user?' % self.pid ) return raise e
def _copyxattr(src, dst, *, follow_symlinks=True): """Copy extended filesystem attributes from `src` to `dst`. Overwrite existing attributes. If `follow_symlinks` is false, symlinks won't be followed. """ try: names = os.listxattr(src, follow_symlinks=follow_symlinks) except OSError as e: if e.errno not in (errno.ENOTSUP, errno.ENODATA): raise return for name in names: try: value = os.getxattr(src, name, follow_symlinks=follow_symlinks) os.setxattr(dst, name, value, follow_symlinks=follow_symlinks) except OSError as e: if e.errno not in (errno.EPERM, errno.ENOTSUP, errno.ENODATA): raise
def test_track_cannot_read(no_sleep, mock_mainfunc, ptmpdir): _, _, inotifier = mock_mainfunc def add_watch(*args, **kwargs): exc = IOError("Hello?") exc.errno = errno.EPERM raise exc inotifier.add_watch.side_effect = add_watch app = get_app() app.destination_path = ptmpdir.join("filename").strpath with pytest.raises(IOError): app.track()
def live(self): if not self.proc_path: return self.info("Proc path: %s" % self.proc_path) key = choice(self.proc_keys) filename = path_join(self.proc_path, key) data = self.generator.createValue() self.info("Write data in %s: (len=%s) %r" % (filename, len(data), data)) try: output = open(filename, 'w') output.write(data) output.close() except IOError, err: if err.errno in (EINVAL, EPERM): pass elif err.errno in (ENOENT, EACCES): self.error("Unable to write %s: %s" % (filename, err)) self.removeKey(key) else: raise
def queryWirelessDevice(self,iface): try: from pythonwifi.iwlibs import Wireless import errno except ImportError: return False else: try: ifobj = Wireless(iface) # a Wireless NIC Object wlanresponse = ifobj.getAPaddr() except IOError, (error_no, error_str): if error_no in (errno.EOPNOTSUPP, errno.ENODEV, errno.EPERM): return False else: print "error: ",error_no,error_str return True else: return True
def graph(self, uuid=None, hook=True, ctx=None, user=None, roles=None, **kwargs): if uuid is None and kwargs.get('create', False): uuid = uuidgen() for k,v in self.graph_opts.iteritems(): if k not in kwargs: kwargs[k] = v if hook: kwargs['hooks'] = CollectionHooks(uuid, self) try: g = Graph(self.graph_path(uuid), **kwargs) except: self.remove(uuid) if ctx is None else ctx.remove(uuid) raise if user is not None: # new graph - do not check creds if g.updated: pass else: if not self.user_allowed(g, user, roles): g.close() raise OSError(errno.EPERM, 'Permission denied', uuid) return g
def get_all_inodes(self): inodes = {} for pid in pids(): try: inodes.update(self.get_proc_inodes(pid)) except OSError as err: # os.listdir() is gonna raise a lot of access denied # exceptions in case of unprivileged user; that's fine # as we'll just end up returning a connection with PID # and fd set to None anyway. # Both netstat -an and lsof does the same so it's # unlikely we can do any better. # ENOENT just means a PID disappeared on us. if err.errno not in ( errno.ENOENT, errno.ESRCH, errno.EPERM, errno.EACCES): raise return inodes
def wrap_exceptions(fun): """Decorator which translates bare OSError and IOError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except EnvironmentError as err: # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. if err.errno in (errno.ENOENT, errno.ESRCH): raise NoSuchProcess(self.pid, self._name) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper
def exe(self): try: return readlink("%s/%s/exe" % (self._procfs_path, self.pid)) except OSError as err: if err.errno in (errno.ENOENT, errno.ESRCH): # no such file error; might be raised also if the # path actually exists for system processes with # low pids (about 0-20) if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)): return "" else: if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise
def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: if err.errno == errno.ESRCH: if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper
def _send_signal(self, sig): if self.pid == 0: # see "man 2 kill" raise ValueError( "preventing sending signal to process with PID 0 as it " "would affect every process in the process group of the " "calling process (os.getpid()) instead of PID 0") try: os.kill(self.pid, sig) except OSError as err: if err.errno == errno.ESRCH: if OPENBSD and pid_exists(self.pid): # We do this because os.kill() lies in case of # zombie processes. raise ZombieProcess(self.pid, self._name, self._ppid) else: self._gone = True raise NoSuchProcess(self.pid, self._name) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise
def wrap_exceptions(fun): """Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. """ def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except EnvironmentError as err: # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. if err.errno in (errno.ENOENT, errno.ESRCH): if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper
def _try_except_permissionerror_iter(try_iter, except_iter): if sys.version_info >= (3, 3): try: for x in try_iter(): yield x except PermissionError as exc: for x in except_iter(exc): yield x else: try: for x in try_iter(): yield x except EnvironmentError as exc: if exc.errno not in (EPERM, EACCES): raise else: for x in except_iter(exc): yield x
def set_file_utime(filename, desired_time): """ Set the utime of a file, and if it fails, raise a more explicit error. :param filename: the file to modify :param desired_time: the epoch timestamp to set for atime and mtime. :raises: SetFileUtimeError: if you do not have permission (errno 1) :raises: OSError: for all errors other than errno 1 """ try: os.utime(filename, (desired_time, desired_time)) except OSError as e: # Only raise a more explicit exception when it is a permission issue. if e.errno != errno.EPERM: raise e raise SetFileUtimeError( ("The file was downloaded, but attempting to modify the " "utime of the file failed. Is the file owned by another user?"))
def scan_and_print_neighbors(net, interface, timeout=1): global ips_o print_fmt("\n\033[94m[ARP]\033[0m %s sur %s" % (net, interface)) try: ans, unans = scapy.layers.l2.arping(net, iface=interface, timeout=timeout, verbose=False) for s, r in ans.res: line = r.sprintf("%Ether.src% %ARP.psrc%") ips_o.append(line.split(' ')[2]) line = mac_address_id(line) try: hostname = socket.gethostbyaddr(r.psrc) line += " " + hostname[0] except socket.herror: pass except KeyboardInterrupt: print '\033[91m[-]\033[0m L\'utilisateur a choisi l\'interruption du process.' break logger.info("\033[96m[ONLINE]\033[0m " + line) except socket.error as e: if e.errno == errno.EPERM: logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror) else: raise
def checkhost(ip): global ips_o conf.verb = 0 try: ping, no = sr(IP(dst=ip)/ICMP(), timeout=1.5, retry=-2) if ping.res: logger.info("\033[96m[ONLINE]\033[0m Cible: " + ip) ips_o.append(ip) except socket.error as e: if e.errno == errno.EPERM: logger.error("\033[91m[-]\033[0m %s. Vous n'etes pas root?", e.strerror) else: pass except Exception as e: logger.error("\033[91m[-]\033[0m Erreur Checkhost() --> {}.".format(e.__class__)) pass
def run(self, sync): app = sync.app with app.db.getSession() as session: change = session.getChange(self.key) if not change: return repo = gitrepo.get_repo(change.project.name, app.config) self.log.info("Pruning %s change %s status:%s updated:%s" % ( change.project.name, change.number, change.status, change.updated)) change_ref = None for revision in change.revisions: if change_ref is None: change_ref = '/'.join(revision.fetch_ref.split('/')[:-1]) self.log.info("Deleting %s ref %s" % ( change.project.name, revision.fetch_ref)) repo.deleteRef(revision.fetch_ref) self.log.info("Deleting %s ref %s" % ( change.project.name, change_ref)) try: repo.deleteRef(change_ref) except OSError as e: if e.errno not in [errno.EISDIR, errno.EPERM]: raise session.delete(change)
def test_socket_busy_on_accept(self, monkeypatch): accept_responses = [ lambda: MockUtils.raise_(socket.error(errno.ENOBUFS, "fatal error message")), lambda: MockUtils.raise_(socket.error(errno.EAGAIN, "busy, try accept again")), lambda: MockUtils.raise_(socket.error(errno.EPERM, "rejected, but try accept again")) ] if sys.platform != 'win32': monkeypatch.setattr(os, 'fork', lambda: 0) monkeypatch.setattr(socket, 'socket', lambda af, st: self.socket) self.socket.accept = lambda: accept_responses.pop()() try: RLXPort.listen(('localhost', 7000)) assert False except Exception as e: traceback.format_exc() assert str(e) == '[Errno %d] fatal error message' % errno.ENOBUFS
def test_initgroups(self): # It takes a string and an integer; check that it raises a TypeError # for other argument lists. self.assertRaises(TypeError, posix.initgroups) self.assertRaises(TypeError, posix.initgroups, None) self.assertRaises(TypeError, posix.initgroups, 3, "foo") self.assertRaises(TypeError, posix.initgroups, "foo", 3, object()) # If a non-privileged user invokes it, it should fail with OSError # EPERM. if os.getuid() != 0: name = pwd.getpwuid(posix.getuid()).pw_name try: posix.initgroups(name, 13) except OSError as e: self.assertEqual(e.errno, errno.EPERM) else: self.fail("Expected OSError to be raised by initgroups")
def validate(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: try: wpid = int(f.read()) except ValueError: return try: os.kill(wpid, 0) return wpid except OSError as e: if e.args[0] == errno.EPERM: return wpid if e.args[0] == errno.ESRCH: return raise except IOError as e: if e.args[0] == errno.ENOENT: return raise
def test_isfile_strict(self): from psutil._common import isfile_strict this_file = os.path.abspath(__file__) assert isfile_strict(this_file) assert not isfile_strict(os.path.dirname(this_file)) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EPERM, "foo")): self.assertRaises(OSError, isfile_strict, this_file) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EACCES, "foo")): self.assertRaises(OSError, isfile_strict, this_file) with mock.patch('psutil._common.os.stat', side_effect=OSError(errno.EINVAL, "foo")): assert not isfile_strict(this_file) with mock.patch('psutil._common.stat.S_ISREG', return_value=False): assert not isfile_strict(this_file)
def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except OSError as err: if self.pid == 0: if 0 in pids(): raise AccessDenied(self.pid, self._name) else: raise if err.errno == errno.ESRCH: if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) raise return wrapper