Python errno.EPERM Examples
The following are 30
code examples of errno.EPERM().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
errno
, or try the search function
.
Example #1
Source File: shutil.py From jawfish with MIT License | 7 votes |
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
Example #2
Source File: shutil.py From kobo-predict with BSD 2-Clause "Simplified" License | 7 votes |
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
Example #3
Source File: _pslinux.py From vnpy_crypto with MIT License | 6 votes |
def ppid_map(): """Obtain a {pid: ppid, ...} dict for all running processes in one shot. Used to speed up Process.children(). """ ret = {} procfs_path = get_procfs_path() for pid in pids(): try: with open_binary("%s/%s/stat" % (procfs_path, pid)) as f: data = f.read() except EnvironmentError as err: # Note: we should be able to access /stat for all processes # aka it's unlikely we'll bump into EPERM, which is good. if err.errno not in (errno.ENOENT, errno.ESRCH): raise else: rpar = data.rfind(b')') dset = data[rpar + 2:].split() ppid = int(dset[1]) ret[pid] = ppid return ret
Example #4
Source File: test_posix.py From oss-ftp with MIT License | 6 votes |
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: try: name = pwd.getpwuid(posix.getuid()).pw_name except KeyError: # the current UID may not have a pwd entry raise unittest.SkipTest("need a pwd entry") 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")
Example #5
Source File: __init__.py From python-netsurv with MIT License | 6 votes |
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
Example #6
Source File: test_import.py From oss-ftp with MIT License | 6 votes |
def _test_UNC_path(self): with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f: f.write("testdata = 'test_trailing_slash'") # Create the UNC path, like \\myhost\c$\foo\bar. path = os.path.abspath(self.path) import socket hn = socket.gethostname() drive = path[0] unc = "\\\\%s\\%s$"%(hn, drive) unc += path[2:] try: os.listdir(unc) except OSError as e: if e.errno in (errno.EPERM, errno.EACCES): # See issue #15338 self.skipTest("cannot access administrative share %r" % (unc,)) raise sys.path.append(path) mod = __import__("test_trailing_slash") self.assertEqual(mod.testdata, 'test_trailing_slash') unload("test_trailing_slash")
Example #7
Source File: static_files_handler_test.py From browserscope with Apache License 2.0 | 6 votes |
def test_no_permission_read(self): url_map = appinfo.URLMap(url='/', static_files='index.html') h = static_files_handler.StaticContentHandler( root_path=None, url_map=url_map, url_pattern='/$') os.path.getmtime('/home/appdir/index.html').AndReturn(12345.6) error = IOError() error.errno = errno.EPERM static_files_handler.StaticContentHandler._read_file( '/home/appdir/index.html').AndRaise(error) self.mox.ReplayAll() self.assertResponse('403 Forbidden', {}, '', h._handle_path, '/home/appdir/index.html', {'REQUEST_METHOD': 'GET', 'PATH_INFO': '/'}) self.mox.VerifyAll()
Example #8
Source File: test_posix.py From oss-ftp with MIT License | 6 votes |
def _test_chflags_regular_file(self, chflags_func, target_file): st = os.stat(target_file) self.assertTrue(hasattr(st, 'st_flags')) # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE. try: chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE) except OSError as err: if err.errno != errno.EOPNOTSUPP: raise msg = 'chflag UF_IMMUTABLE not supported by underlying fs' self.skipTest(msg) try: new_st = os.stat(target_file) self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags) try: fd = open(target_file, 'w+') except IOError as e: self.assertEqual(e.errno, errno.EPERM) finally: posix.chflags(target_file, st.st_flags)
Example #9
Source File: asyncioreactor.py From Safejumper-for-Desktop with GNU General Public License v2.0 | 6 votes |
def addReader(self, reader): if reader in self._readers.keys() or \ reader in self._continuousPolling._readers: return fd = reader.fileno() try: self._asyncioEventloop.add_reader(fd, callWithLogger, reader, self._readOrWrite, reader, True) self._readers[reader] = fd except IOError as e: self._unregisterFDInAsyncio(fd) if e.errno == errno.EPERM: # epoll(7) doesn't support certain file descriptors, # e.g. filesystem files, so for those we just poll # continuously: self._continuousPolling.addReader(reader) else: raise
Example #10
Source File: cross_platform_process.py From sublime-gulp with MIT License | 6 votes |
def _pid_exists(self): if not self.pid: return False if sublime.platform() == "windows": taskkill = subprocess.Popen(['C:\\Windows\\system32\\tasklist.exe', '/FI', 'PID eq %s' % self.pid, '/FO', 'CSV'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (stdout, stderr) = taskkill.communicate() failed = taskkill.returncode == 127 or stderr found = str(self.pid) in CrossPlatformCodecs.force_decode(stdout) return found or failed else: try: os.kill(self.pid, 0) except OSError as err: if err.errno == errno.ESRCH: return False elif err.errno == errno.EPERM: return True else: raise else: return True
Example #11
Source File: rarfile.py From Lector with GNU General Public License v3.0 | 6 votes |
def custom_popen(cmd): """Disconnect cmd from parent fds, read only from stdout. """ # needed for py2exe creationflags = 0 if sys.platform == 'win32': creationflags = 0x08000000 # CREATE_NO_WINDOW # run command try: p = Popen(cmd, bufsize=0, stdout=PIPE, stdin=PIPE, stderr=STDOUT, creationflags=creationflags) except OSError as ex: if ex.errno == errno.ENOENT: raise RarCannotExec("Unrar not installed? (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL) if ex.errno == errno.EACCES or ex.errno == errno.EPERM: raise RarCannotExec("Cannot execute unrar (rarfile.UNRAR_TOOL=%r)" % UNRAR_TOOL) raise return p
Example #12
Source File: test_posix.py From BinderFilter with MIT License | 6 votes |
def _test_chflags_regular_file(self, chflags_func, target_file): st = os.stat(target_file) self.assertTrue(hasattr(st, 'st_flags')) # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE. try: chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE) except OSError as err: if err.errno != errno.EOPNOTSUPP: raise msg = 'chflag UF_IMMUTABLE not supported by underlying fs' self.skipTest(msg) try: new_st = os.stat(target_file) self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags) try: fd = open(target_file, 'w+') except IOError as e: self.assertEqual(e.errno, errno.EPERM) finally: posix.chflags(target_file, st.st_flags)
Example #13
Source File: test_posix.py From BinderFilter with MIT License | 6 votes |
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: try: name = pwd.getpwuid(posix.getuid()).pw_name except KeyError: # the current UID may not have a pwd entry raise unittest.SkipTest("need a pwd entry") 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")
Example #14
Source File: test_misc.py From psutil with BSD 3-Clause "New" or "Revised" License | 6 votes |
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.ENOENT, "foo")): assert not isfile_strict(this_file) with mock.patch('psutil._common.stat.S_ISREG', return_value=False): assert not isfile_strict(this_file)
Example #15
Source File: test_import.py From BinderFilter with MIT License | 6 votes |
def _test_UNC_path(self): with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f: f.write("testdata = 'test_trailing_slash'") # Create the UNC path, like \\myhost\c$\foo\bar. path = os.path.abspath(self.path) import socket hn = socket.gethostname() drive = path[0] unc = "\\\\%s\\%s$"%(hn, drive) unc += path[2:] try: os.listdir(unc) except OSError as e: if e.errno in (errno.EPERM, errno.EACCES): # See issue #15338 self.skipTest("cannot access administrative share %r" % (unc,)) raise sys.path.append(path) mod = __import__("test_trailing_slash") self.assertEqual(mod.testdata, 'test_trailing_slash') unload("test_trailing_slash")
Example #16
Source File: test_import.py From ironpython2 with Apache License 2.0 | 6 votes |
def _test_UNC_path(self): with open(os.path.join(self.path, 'test_trailing_slash.py'), 'w') as f: f.write("testdata = 'test_trailing_slash'") # Create the UNC path, like \\myhost\c$\foo\bar. path = os.path.abspath(self.path) import socket hn = socket.gethostname() drive = path[0] unc = "\\\\%s\\%s$"%(hn, drive) unc += path[2:] try: os.listdir(unc) except OSError as e: if e.errno in (errno.EPERM, errno.EACCES, errno.ENOENT): # See issue #15338 self.skipTest("cannot access administrative share %r" % (unc,)) raise sys.path.append(path) mod = __import__("test_trailing_slash") self.assertEqual(mod.testdata, 'test_trailing_slash') unload("test_trailing_slash")
Example #17
Source File: test_posix.py From ironpython2 with Apache License 2.0 | 6 votes |
def _test_chflags_regular_file(self, chflags_func, target_file): st = os.stat(target_file) self.assertTrue(hasattr(st, 'st_flags')) # ZFS returns EOPNOTSUPP when attempting to set flag UF_IMMUTABLE. try: chflags_func(target_file, st.st_flags | stat.UF_IMMUTABLE) except OSError as err: if err.errno != errno.EOPNOTSUPP: raise msg = 'chflag UF_IMMUTABLE not supported by underlying fs' self.skipTest(msg) try: new_st = os.stat(target_file) self.assertEqual(st.st_flags | stat.UF_IMMUTABLE, new_st.st_flags) try: fd = open(target_file, 'w+') except IOError as e: self.assertEqual(e.errno, errno.EPERM) finally: posix.chflags(target_file, st.st_flags)
Example #18
Source File: test_site.py From ironpython2 with Apache License 2.0 | 6 votes |
def setUpModule(): global OLD_SYS_PATH OLD_SYS_PATH = sys.path[:] if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE): # need to add user site directory for tests try: os.makedirs(site.USER_SITE) # modify sys.path: will be restored by tearDownModule() site.addsitedir(site.USER_SITE) except OSError as exc: if exc.errno in (errno.EACCES, errno.EPERM): raise unittest.SkipTest('unable to create user site directory (%r): %s' % (site.USER_SITE, exc)) else: raise
Example #19
Source File: lanscan.py From lanscan with MIT License | 6 votes |
def scan(self, get_vendor, do_portscan, timeout=1): try: ans, unans = scapy.layers.l2.arping(self.cidr, iface=self.interface_name, timeout=timeout, verbose=False) for s, r in ans.res: self.neighbours.append(Host(r.psrc, r.src)) except socket.error as e: if e.errno == errno.EPERM: # Operation not permitted message = ("Error: {}\n" "Run as root or - better - set the necessary capabilities for the python interpreter used and tcpdump.\n" "Example: setcap cap_net_raw=eip /usr/bin/python3\n" "Example: setcap cap_net_raw=eip $(which tcpdump)\n" "You may need to install the libcap-progs package").format(e.strerror) exit_n(message, 2) else: raise self.neighbours.sort(key=lambda x: x.sort_value) if get_vendor: self.set_vendor_in_neighbours() if do_portscan: self.set_open_ports_in_neigbours() self.set_is_alive_in_neigbours()
Example #20
Source File: _psaix.py From vnpy_crypto with MIT License | 6 votes |
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: # support for private module import if (NoSuchProcess is None or AccessDenied is None or ZombieProcess is None): raise # 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
Example #21
Source File: __init__.py From vnpy_crypto with MIT License | 6 votes |
def _send_signal(self, sig): assert not self.pid < 0, self.pid 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
Example #22
Source File: _pslinux.py From vnpy_crypto with MIT License | 6 votes |
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
Example #23
Source File: _pslinux.py From vnpy_crypto with MIT License | 6 votes |
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: if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(self.pid, self._name) # ESRCH (no such process) can be raised on read() if # process is gone in the meantime. if err.errno == errno.ESRCH: raise NoSuchProcess(self.pid, self._name) # ENOENT (no such file or directory) can be raised on open(). if err.errno == errno.ENOENT and not os.path.exists("%s/%s" % ( self._procfs_path, self.pid)): raise NoSuchProcess(self.pid, self._name) # Note: zombies will keep existing under /proc until they're # gone so there's no way to distinguish them in here. raise return wrapper
Example #24
Source File: _psbsd.py From vnpy_crypto with MIT License | 6 votes |
def wrap_exceptions_procfs(inst): """Same as above, for routines relying on reading /proc fs.""" try: yield 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(inst.pid): raise NoSuchProcess(inst.pid, inst._name) else: raise ZombieProcess(inst.pid, inst._name, inst._ppid) if err.errno in (errno.EPERM, errno.EACCES): raise AccessDenied(inst.pid, inst._name) raise
Example #25
Source File: _pslinux.py From vnpy_crypto with MIT License | 6 votes |
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
Example #26
Source File: __init__.py From python-netsurv with MIT License | 6 votes |
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
Example #27
Source File: netns_wrapper.py From neutron-vpnaas with Apache License 2.0 | 5 votes |
def filter_command(command, rootwrap_config): # Load rootwrap configuration try: rawconfig = ConfigParser.RawConfigParser() rawconfig.read(rootwrap_config) rw_config = wrapper.RootwrapConfig(rawconfig) except ValueError as exc: LOG.error('Incorrect value in %(config)s: %(exc)s', {'config': rootwrap_config, 'exc': exc}) sys.exit(errno.EINVAL) except ConfigParser.Error: LOG.error('Incorrect configuration file: %(config)s', {'config': rootwrap_config}) sys.exit(errno.EINVAL) # Check if command matches any of the loaded filters filters = wrapper.load_filters(rw_config.filters_path) try: wrapper.match_filter(filters, command, exec_dirs=rw_config.exec_dirs) except wrapper.FilterMatchNotExecutable as exc: LOG.error('Command %(command)s is not executable: ' '%(path)s (filter match = %(name)s)', {'command': command, 'path': exc.match.exec_path, 'name': exc.match.name}) sys.exit(errno.EINVAL) except wrapper.NoFilterMatched: LOG.error('Unauthorized command: %(cmd)s (no filter matched)', {'cmd': command}) sys.exit(errno.EPERM)
Example #28
Source File: _common.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError as err: if err.errno in (errno.EPERM, errno.EACCES): raise return False else: return stat.S_ISREG(st.st_mode)
Example #29
Source File: _pswindows.py From psutil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def is_permission_err(exc): """Return True if this is a permission error.""" assert isinstance(exc, OSError), exc # On Python 2 OSError doesn't always have 'winerror'. Sometimes # it does, in which case the original exception was WindowsError # (which is a subclass of OSError). return exc.errno in (errno.EPERM, errno.EACCES) or \ getattr(exc, "winerror", -1) in (cext.ERROR_ACCESS_DENIED, cext.ERROR_PRIVILEGE_NOT_HELD)
Example #30
Source File: test_windows.py From vnpy_crypto with MIT License | 5 votes |
def test_memory_info(self): mem_1 = psutil.Process(self.pid).memory_info() with mock.patch("psutil._psplatform.cext.proc_memory_info", side_effect=OSError(errno.EPERM, "msg")) as fun: mem_2 = psutil.Process(self.pid).memory_info() self.assertEqual(len(mem_1), len(mem_2)) for i in range(len(mem_1)): self.assertGreaterEqual(mem_1[i], 0) self.assertGreaterEqual(mem_2[i], 0) self.assertAlmostEqual(mem_1[i], mem_2[i], delta=512) assert fun.called