index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
11,261 | rarfile | __init__ | null | def __init__(self, key, iv):
if _have_crypto == 2:
self.decrypt = AES.new(key, AES.MODE_CBC, iv).decrypt
else:
ciph = Cipher(algorithms.AES(key), modes.CBC(iv), default_backend())
self.decrypt = ciph.decryptor().update
| (self, key, iv) |
11,262 | rarfile | BadRarFile | Incorrect data in archive. | class BadRarFile(Error):
"""Incorrect data in archive."""
| null |
11,263 | rarfile | BadRarName | Cannot guess multipart name components. | class BadRarName(Error):
"""Cannot guess multipart name components."""
| null |
11,264 | rarfile | Blake2SP | Blake2sp hash context.
| class Blake2SP:
"""Blake2sp hash context.
"""
__slots__ = ["_thread", "_buf", "_cur", "_digest"]
digest_size = 32
block_size = 64
parallelism = 8
def __init__(self, data=None):
self._buf = b""
self._cur = 0
self._digest = None
self._thread = []
for i in range(self.parallelism):
ctx = self._blake2s(i, 0, i == (self.parallelism - 1))
self._thread.append(ctx)
if data:
self.update(data)
def _blake2s(self, ofs, depth, is_last):
return blake2s(node_offset=ofs, node_depth=depth, last_node=is_last,
depth=2, inner_size=32, fanout=self.parallelism)
def _add_block(self, blk):
self._thread[self._cur].update(blk)
self._cur = (self._cur + 1) % self.parallelism
def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
self._buf += view.tobytes()
return
self._add_block(self._buf + view[:need].tobytes())
view = view[need:]
while len(view) >= bs:
self._add_block(view[:bs])
view = view[bs:]
self._buf = view.tobytes()
def digest(self):
"""Return final digest value.
"""
if self._digest is None:
if self._buf:
self._add_block(self._buf)
self._buf = b""
ctx = self._blake2s(0, 1, True)
for t in self._thread:
ctx.update(t.digest())
self._digest = ctx.digest()
return self._digest
def hexdigest(self):
"""Hexadecimal digest."""
return hexlify(self.digest()).decode("ascii")
| (data=None) |
11,265 | rarfile | __init__ | null | def __init__(self, data=None):
self._buf = b""
self._cur = 0
self._digest = None
self._thread = []
for i in range(self.parallelism):
ctx = self._blake2s(i, 0, i == (self.parallelism - 1))
self._thread.append(ctx)
if data:
self.update(data)
| (self, data=None) |
11,266 | rarfile | _add_block | null | def _add_block(self, blk):
self._thread[self._cur].update(blk)
self._cur = (self._cur + 1) % self.parallelism
| (self, blk) |
11,267 | rarfile | _blake2s | null | def _blake2s(self, ofs, depth, is_last):
return blake2s(node_offset=ofs, node_depth=depth, last_node=is_last,
depth=2, inner_size=32, fanout=self.parallelism)
| (self, ofs, depth, is_last) |
11,268 | rarfile | digest | Return final digest value.
| def digest(self):
"""Return final digest value.
"""
if self._digest is None:
if self._buf:
self._add_block(self._buf)
self._buf = b""
ctx = self._blake2s(0, 1, True)
for t in self._thread:
ctx.update(t.digest())
self._digest = ctx.digest()
return self._digest
| (self) |
11,269 | rarfile | hexdigest | Hexadecimal digest. | def hexdigest(self):
"""Hexadecimal digest."""
return hexlify(self.digest()).decode("ascii")
| (self) |
11,270 | rarfile | update | Hash data.
| def update(self, data):
"""Hash data.
"""
view = memoryview(data)
bs = self.block_size
if self._buf:
need = bs - len(self._buf)
if len(view) < need:
self._buf += view.tobytes()
return
self._add_block(self._buf + view[:need].tobytes())
view = view[need:]
while len(view) >= bs:
self._add_block(view[:bs])
view = view[bs:]
self._buf = view.tobytes()
| (self, data) |
11,271 | rarfile | CRC32Context | Hash context that uses CRC32. | class CRC32Context:
"""Hash context that uses CRC32."""
__slots__ = ["_crc"]
def __init__(self, data=None):
self._crc = 0
if data:
self.update(data)
def update(self, data):
"""Process data."""
self._crc = crc32(data, self._crc)
def digest(self):
"""Final hash."""
return self._crc
def hexdigest(self):
"""Hexadecimal digest."""
return "%08x" % self.digest()
| (data=None) |
11,272 | rarfile | __init__ | null | def __init__(self, data=None):
self._crc = 0
if data:
self.update(data)
| (self, data=None) |
11,273 | rarfile | digest | Final hash. | def digest(self):
"""Final hash."""
return self._crc
| (self) |
11,274 | rarfile | hexdigest | Hexadecimal digest. | def hexdigest(self):
"""Hexadecimal digest."""
return "%08x" % self.digest()
| (self) |
11,275 | rarfile | update | Process data. | def update(self, data):
"""Process data."""
self._crc = crc32(data, self._crc)
| (self, data) |
11,276 | rarfile | CommonParser | Shared parser parts. | class CommonParser:
"""Shared parser parts."""
_main = None
_hdrenc_main = None
_needs_password = False
_fd = None
_expect_sig = None
_parse_error = None
_password = None
comment = None
def __init__(self, rarfile, password, crc_check, charset, strict,
info_cb, sfx_offset, part_only):
self._rarfile = rarfile
self._password = password
self._crc_check = crc_check
self._charset = charset
self._strict = strict
self._info_callback = info_cb
self._info_list = []
self._info_map = {}
self._vol_list = []
self._sfx_offset = sfx_offset
self._part_only = part_only
def is_solid(self):
"""Returns True if archive uses solid compression.
"""
if self._main:
if self._main.flags & RAR_MAIN_SOLID:
return True
return False
def has_header_encryption(self):
"""Returns True if headers are encrypted
"""
if self._hdrenc_main:
return True
if self._main:
if self._main.flags & RAR_MAIN_PASSWORD:
return True
return False
def setpassword(self, pwd):
"""Set cached password."""
self._password = pwd
def volumelist(self):
"""Volume files"""
return self._vol_list
def needs_password(self):
"""Is password required"""
return self._needs_password
def strerror(self):
"""Last error"""
return self._parse_error
def infolist(self):
"""List of RarInfo records.
"""
return self._info_list
def getinfo(self, member):
"""Return RarInfo for filename
"""
if isinstance(member, RarInfo):
fname = member.filename
elif isinstance(member, Path):
fname = str(member)
else:
fname = member
if fname.endswith("/"):
fname = fname.rstrip("/")
try:
return self._info_map[fname]
except KeyError:
raise NoRarEntry("No such file: %s" % fname) from None
def getinfo_orig(self, member):
inf = self.getinfo(member)
if inf.file_redir:
redir_type, redir_flags, redir_name = inf.file_redir
# cannot leave to unrar as it expects copied file to exist
if redir_type in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(redir_name)
return inf
def parse(self):
"""Process file."""
self._fd = None
try:
self._parse_real()
finally:
if self._fd:
self._fd.close()
self._fd = None
def _parse_real(self):
"""Actually read file.
"""
fd = XFile(self._rarfile)
self._fd = fd
fd.seek(self._sfx_offset, 0)
sig = fd.read(len(self._expect_sig))
if sig != self._expect_sig:
raise NotRarFile("Not a Rar archive")
volume = 0 # first vol (.rar) is 0
more_vols = False
endarc = False
volfile = self._rarfile
self._vol_list = [self._rarfile]
raise_need_first_vol = False
while True:
if endarc:
h = None # don"t read past ENDARC
else:
h = self._parse_header(fd)
if not h:
if raise_need_first_vol:
# did not find ENDARC with VOLNR
raise NeedFirstVolume("Need to start from first volume", None)
if more_vols and not self._part_only:
volume += 1
fd.close()
try:
volfile = self._next_volname(volfile)
fd = XFile(volfile)
except IOError:
self._set_error("Cannot open next volume: %s", volfile)
break
self._fd = fd
sig = fd.read(len(self._expect_sig))
if sig != self._expect_sig:
self._set_error("Invalid volume sig: %s", volfile)
break
more_vols = False
endarc = False
self._vol_list.append(volfile)
self._main = None
self._hdrenc_main = None
continue
break
h.volume = volume
h.volume_file = volfile
if h.type == RAR_BLOCK_MAIN and not self._main:
self._main = h
if volume == 0 and (h.flags & RAR_MAIN_NEWNUMBERING) and not self._part_only:
# RAR 2.x does not set FIRSTVOLUME,
# so check it only if NEWNUMBERING is used
if (h.flags & RAR_MAIN_FIRSTVOLUME) == 0:
if getattr(h, "main_volume_number", None) is not None:
# rar5 may have more info
raise NeedFirstVolume(
"Need to start from first volume (current: %r)"
% (h.main_volume_number,),
h.main_volume_number
)
# delay raise until we have volnr from ENDARC
raise_need_first_vol = True
if h.flags & RAR_MAIN_PASSWORD:
self._needs_password = True
if not self._password:
break
elif h.type == RAR_BLOCK_ENDARC:
# use flag, but also allow RAR 2.x logic below to trigger
if h.flags & RAR_ENDARC_NEXT_VOLUME:
more_vols = True
endarc = True
if raise_need_first_vol and (h.flags & RAR_ENDARC_VOLNR) > 0:
raise NeedFirstVolume(
"Need to start from first volume (current: %r)"
% (h.endarc_volnr,),
h.endarc_volnr
)
elif h.type == RAR_BLOCK_FILE:
# RAR 2.x does not write RAR_BLOCK_ENDARC
if h.flags & RAR_FILE_SPLIT_AFTER:
more_vols = True
# RAR 2.x does not set RAR_MAIN_FIRSTVOLUME
if volume == 0 and h.flags & RAR_FILE_SPLIT_BEFORE:
if not self._part_only:
raise_need_first_vol = True
if h.needs_password():
self._needs_password = True
# store it
self.process_entry(fd, h)
if self._info_callback:
self._info_callback(h)
# go to next header
if h.add_size > 0:
fd.seek(h.data_offset + h.add_size, 0)
def process_entry(self, fd, item):
"""Examine item, add into lookup cache."""
raise NotImplementedError()
def _decrypt_header(self, fd):
raise NotImplementedError("_decrypt_header")
def _parse_block_header(self, fd):
raise NotImplementedError("_parse_block_header")
def _open_hack(self, inf, pwd):
raise NotImplementedError("_open_hack")
def _parse_header(self, fd):
"""Read single header
"""
try:
# handle encrypted headers
if (self._main and self._main.flags & RAR_MAIN_PASSWORD) or self._hdrenc_main:
if not self._password:
return None
fd = self._decrypt_header(fd)
# now read actual header
return self._parse_block_header(fd)
except struct.error:
self._set_error("Broken header in RAR file")
return None
def _next_volname(self, volfile):
"""Given current vol name, construct next one
"""
if is_filelike(volfile):
raise IOError("Working on single FD")
if self._main.flags & RAR_MAIN_NEWNUMBERING:
return _next_newvol(volfile)
return _next_oldvol(volfile)
def _set_error(self, msg, *args):
if args:
msg = msg % args
self._parse_error = msg
if self._strict:
raise BadRarFile(msg)
def open(self, inf, pwd):
"""Return stream object for file data."""
if inf.file_redir:
redir_type, redir_flags, redir_name = inf.file_redir
# cannot leave to unrar as it expects copied file to exist
if redir_type in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(redir_name)
if not inf:
raise BadRarFile("cannot find copied file")
elif redir_type in (
RAR5_XREDIR_UNIX_SYMLINK, RAR5_XREDIR_WINDOWS_SYMLINK,
RAR5_XREDIR_WINDOWS_JUNCTION,
):
return io.BytesIO(redir_name.encode("utf8"))
if inf.flags & RAR_FILE_SPLIT_BEFORE:
raise NeedFirstVolume("Partial file, please start from first volume: " + inf.filename, None)
# is temp write usable?
use_hack = 1
if not self._main:
use_hack = 0
elif self._main._must_disable_hack():
use_hack = 0
elif inf._must_disable_hack():
use_hack = 0
elif is_filelike(self._rarfile):
pass
elif inf.file_size > HACK_SIZE_LIMIT:
use_hack = 0
elif not USE_EXTRACT_HACK:
use_hack = 0
# now extract
if inf.compress_type == RAR_M0 and (inf.flags & RAR_FILE_PASSWORD) == 0 and inf.file_redir is None:
return self._open_clear(inf)
elif use_hack:
return self._open_hack(inf, pwd)
elif is_filelike(self._rarfile):
return self._open_unrar_membuf(self._rarfile, inf, pwd)
else:
return self._open_unrar(self._rarfile, inf, pwd)
def _open_clear(self, inf):
if FORCE_TOOL:
return self._open_unrar(self._rarfile, inf)
return DirectReader(self, inf)
def _open_hack_core(self, inf, pwd, prefix, suffix):
size = inf.compress_size + inf.header_size
rf = XFile(inf.volume_file, 0)
rf.seek(inf.header_offset)
tmpfd, tmpname = mkstemp(suffix=".rar", dir=HACK_TMP_DIR)
tmpf = os.fdopen(tmpfd, "wb")
try:
tmpf.write(prefix)
while size > 0:
if size > BSIZE:
buf = rf.read(BSIZE)
else:
buf = rf.read(size)
if not buf:
raise BadRarFile("read failed: " + inf.filename)
tmpf.write(buf)
size -= len(buf)
tmpf.write(suffix)
tmpf.close()
rf.close()
except BaseException:
rf.close()
tmpf.close()
os.unlink(tmpname)
raise
return self._open_unrar(tmpname, inf, pwd, tmpname)
def _open_unrar_membuf(self, memfile, inf, pwd):
"""Write in-memory archive to temp file, needed for solid archives.
"""
tmpname = membuf_tempfile(memfile)
return self._open_unrar(tmpname, inf, pwd, tmpname, force_file=True)
def _open_unrar(self, rarfile, inf, pwd=None, tmpfile=None, force_file=False):
"""Extract using unrar
"""
setup = tool_setup()
# not giving filename avoids encoding related problems
fn = None
if not tmpfile or force_file:
fn = inf.filename.replace("/", os.path.sep)
# read from unrar pipe
cmd = setup.open_cmdline(pwd, rarfile, fn)
return PipeReader(self, inf, cmd, tmpfile)
| (rarfile, password, crc_check, charset, strict, info_cb, sfx_offset, part_only) |
11,277 | rarfile | __init__ | null | def __init__(self, rarfile, password, crc_check, charset, strict,
info_cb, sfx_offset, part_only):
self._rarfile = rarfile
self._password = password
self._crc_check = crc_check
self._charset = charset
self._strict = strict
self._info_callback = info_cb
self._info_list = []
self._info_map = {}
self._vol_list = []
self._sfx_offset = sfx_offset
self._part_only = part_only
| (self, rarfile, password, crc_check, charset, strict, info_cb, sfx_offset, part_only) |
11,278 | rarfile | _decrypt_header | null | def _decrypt_header(self, fd):
raise NotImplementedError("_decrypt_header")
| (self, fd) |
11,279 | rarfile | _next_volname | Given current vol name, construct next one
| def _next_volname(self, volfile):
"""Given current vol name, construct next one
"""
if is_filelike(volfile):
raise IOError("Working on single FD")
if self._main.flags & RAR_MAIN_NEWNUMBERING:
return _next_newvol(volfile)
return _next_oldvol(volfile)
| (self, volfile) |
11,280 | rarfile | _open_clear | null | def _open_clear(self, inf):
if FORCE_TOOL:
return self._open_unrar(self._rarfile, inf)
return DirectReader(self, inf)
| (self, inf) |
11,281 | rarfile | _open_hack | null | def _open_hack(self, inf, pwd):
raise NotImplementedError("_open_hack")
| (self, inf, pwd) |
11,282 | rarfile | _open_hack_core | null | def _open_hack_core(self, inf, pwd, prefix, suffix):
size = inf.compress_size + inf.header_size
rf = XFile(inf.volume_file, 0)
rf.seek(inf.header_offset)
tmpfd, tmpname = mkstemp(suffix=".rar", dir=HACK_TMP_DIR)
tmpf = os.fdopen(tmpfd, "wb")
try:
tmpf.write(prefix)
while size > 0:
if size > BSIZE:
buf = rf.read(BSIZE)
else:
buf = rf.read(size)
if not buf:
raise BadRarFile("read failed: " + inf.filename)
tmpf.write(buf)
size -= len(buf)
tmpf.write(suffix)
tmpf.close()
rf.close()
except BaseException:
rf.close()
tmpf.close()
os.unlink(tmpname)
raise
return self._open_unrar(tmpname, inf, pwd, tmpname)
| (self, inf, pwd, prefix, suffix) |
11,283 | rarfile | _open_unrar | Extract using unrar
| def _open_unrar(self, rarfile, inf, pwd=None, tmpfile=None, force_file=False):
"""Extract using unrar
"""
setup = tool_setup()
# not giving filename avoids encoding related problems
fn = None
if not tmpfile or force_file:
fn = inf.filename.replace("/", os.path.sep)
# read from unrar pipe
cmd = setup.open_cmdline(pwd, rarfile, fn)
return PipeReader(self, inf, cmd, tmpfile)
| (self, rarfile, inf, pwd=None, tmpfile=None, force_file=False) |
11,284 | rarfile | _open_unrar_membuf | Write in-memory archive to temp file, needed for solid archives.
| def _open_unrar_membuf(self, memfile, inf, pwd):
"""Write in-memory archive to temp file, needed for solid archives.
"""
tmpname = membuf_tempfile(memfile)
return self._open_unrar(tmpname, inf, pwd, tmpname, force_file=True)
| (self, memfile, inf, pwd) |
11,285 | rarfile | _parse_block_header | null | def _parse_block_header(self, fd):
raise NotImplementedError("_parse_block_header")
| (self, fd) |
11,286 | rarfile | _parse_header | Read single header
| def _parse_header(self, fd):
"""Read single header
"""
try:
# handle encrypted headers
if (self._main and self._main.flags & RAR_MAIN_PASSWORD) or self._hdrenc_main:
if not self._password:
return None
fd = self._decrypt_header(fd)
# now read actual header
return self._parse_block_header(fd)
except struct.error:
self._set_error("Broken header in RAR file")
return None
| (self, fd) |
11,287 | rarfile | _parse_real | Actually read file.
| def _parse_real(self):
"""Actually read file.
"""
fd = XFile(self._rarfile)
self._fd = fd
fd.seek(self._sfx_offset, 0)
sig = fd.read(len(self._expect_sig))
if sig != self._expect_sig:
raise NotRarFile("Not a Rar archive")
volume = 0 # first vol (.rar) is 0
more_vols = False
endarc = False
volfile = self._rarfile
self._vol_list = [self._rarfile]
raise_need_first_vol = False
while True:
if endarc:
h = None # don"t read past ENDARC
else:
h = self._parse_header(fd)
if not h:
if raise_need_first_vol:
# did not find ENDARC with VOLNR
raise NeedFirstVolume("Need to start from first volume", None)
if more_vols and not self._part_only:
volume += 1
fd.close()
try:
volfile = self._next_volname(volfile)
fd = XFile(volfile)
except IOError:
self._set_error("Cannot open next volume: %s", volfile)
break
self._fd = fd
sig = fd.read(len(self._expect_sig))
if sig != self._expect_sig:
self._set_error("Invalid volume sig: %s", volfile)
break
more_vols = False
endarc = False
self._vol_list.append(volfile)
self._main = None
self._hdrenc_main = None
continue
break
h.volume = volume
h.volume_file = volfile
if h.type == RAR_BLOCK_MAIN and not self._main:
self._main = h
if volume == 0 and (h.flags & RAR_MAIN_NEWNUMBERING) and not self._part_only:
# RAR 2.x does not set FIRSTVOLUME,
# so check it only if NEWNUMBERING is used
if (h.flags & RAR_MAIN_FIRSTVOLUME) == 0:
if getattr(h, "main_volume_number", None) is not None:
# rar5 may have more info
raise NeedFirstVolume(
"Need to start from first volume (current: %r)"
% (h.main_volume_number,),
h.main_volume_number
)
# delay raise until we have volnr from ENDARC
raise_need_first_vol = True
if h.flags & RAR_MAIN_PASSWORD:
self._needs_password = True
if not self._password:
break
elif h.type == RAR_BLOCK_ENDARC:
# use flag, but also allow RAR 2.x logic below to trigger
if h.flags & RAR_ENDARC_NEXT_VOLUME:
more_vols = True
endarc = True
if raise_need_first_vol and (h.flags & RAR_ENDARC_VOLNR) > 0:
raise NeedFirstVolume(
"Need to start from first volume (current: %r)"
% (h.endarc_volnr,),
h.endarc_volnr
)
elif h.type == RAR_BLOCK_FILE:
# RAR 2.x does not write RAR_BLOCK_ENDARC
if h.flags & RAR_FILE_SPLIT_AFTER:
more_vols = True
# RAR 2.x does not set RAR_MAIN_FIRSTVOLUME
if volume == 0 and h.flags & RAR_FILE_SPLIT_BEFORE:
if not self._part_only:
raise_need_first_vol = True
if h.needs_password():
self._needs_password = True
# store it
self.process_entry(fd, h)
if self._info_callback:
self._info_callback(h)
# go to next header
if h.add_size > 0:
fd.seek(h.data_offset + h.add_size, 0)
| (self) |
11,288 | rarfile | _set_error | null | def _set_error(self, msg, *args):
if args:
msg = msg % args
self._parse_error = msg
if self._strict:
raise BadRarFile(msg)
| (self, msg, *args) |
11,289 | rarfile | getinfo | Return RarInfo for filename
| def getinfo(self, member):
"""Return RarInfo for filename
"""
if isinstance(member, RarInfo):
fname = member.filename
elif isinstance(member, Path):
fname = str(member)
else:
fname = member
if fname.endswith("/"):
fname = fname.rstrip("/")
try:
return self._info_map[fname]
except KeyError:
raise NoRarEntry("No such file: %s" % fname) from None
| (self, member) |
11,290 | rarfile | getinfo_orig | null | def getinfo_orig(self, member):
inf = self.getinfo(member)
if inf.file_redir:
redir_type, redir_flags, redir_name = inf.file_redir
# cannot leave to unrar as it expects copied file to exist
if redir_type in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(redir_name)
return inf
| (self, member) |
11,291 | rarfile | has_header_encryption | Returns True if headers are encrypted
| def has_header_encryption(self):
"""Returns True if headers are encrypted
"""
if self._hdrenc_main:
return True
if self._main:
if self._main.flags & RAR_MAIN_PASSWORD:
return True
return False
| (self) |
11,292 | rarfile | infolist | List of RarInfo records.
| def infolist(self):
"""List of RarInfo records.
"""
return self._info_list
| (self) |
11,293 | rarfile | is_solid | Returns True if archive uses solid compression.
| def is_solid(self):
"""Returns True if archive uses solid compression.
"""
if self._main:
if self._main.flags & RAR_MAIN_SOLID:
return True
return False
| (self) |
11,294 | rarfile | needs_password | Is password required | def needs_password(self):
"""Is password required"""
return self._needs_password
| (self) |
11,295 | rarfile | open | Return stream object for file data. | def open(self, inf, pwd):
"""Return stream object for file data."""
if inf.file_redir:
redir_type, redir_flags, redir_name = inf.file_redir
# cannot leave to unrar as it expects copied file to exist
if redir_type in (RAR5_XREDIR_FILE_COPY, RAR5_XREDIR_HARD_LINK):
inf = self.getinfo(redir_name)
if not inf:
raise BadRarFile("cannot find copied file")
elif redir_type in (
RAR5_XREDIR_UNIX_SYMLINK, RAR5_XREDIR_WINDOWS_SYMLINK,
RAR5_XREDIR_WINDOWS_JUNCTION,
):
return io.BytesIO(redir_name.encode("utf8"))
if inf.flags & RAR_FILE_SPLIT_BEFORE:
raise NeedFirstVolume("Partial file, please start from first volume: " + inf.filename, None)
# is temp write usable?
use_hack = 1
if not self._main:
use_hack = 0
elif self._main._must_disable_hack():
use_hack = 0
elif inf._must_disable_hack():
use_hack = 0
elif is_filelike(self._rarfile):
pass
elif inf.file_size > HACK_SIZE_LIMIT:
use_hack = 0
elif not USE_EXTRACT_HACK:
use_hack = 0
# now extract
if inf.compress_type == RAR_M0 and (inf.flags & RAR_FILE_PASSWORD) == 0 and inf.file_redir is None:
return self._open_clear(inf)
elif use_hack:
return self._open_hack(inf, pwd)
elif is_filelike(self._rarfile):
return self._open_unrar_membuf(self._rarfile, inf, pwd)
else:
return self._open_unrar(self._rarfile, inf, pwd)
| (self, inf, pwd) |
11,296 | rarfile | parse | Process file. | def parse(self):
"""Process file."""
self._fd = None
try:
self._parse_real()
finally:
if self._fd:
self._fd.close()
self._fd = None
| (self) |
11,297 | rarfile | process_entry | Examine item, add into lookup cache. | def process_entry(self, fd, item):
"""Examine item, add into lookup cache."""
raise NotImplementedError()
| (self, fd, item) |
11,298 | rarfile | setpassword | Set cached password. | def setpassword(self, pwd):
"""Set cached password."""
self._password = pwd
| (self, pwd) |
11,299 | rarfile | strerror | Last error | def strerror(self):
"""Last error"""
return self._parse_error
| (self) |
11,300 | rarfile | volumelist | Volume files | def volumelist(self):
"""Volume files"""
return self._vol_list
| (self) |
11,301 | rarfile | DirectReader | Read uncompressed data directly from archive.
| class DirectReader(RarExtFile):
"""Read uncompressed data directly from archive.
"""
_cur = None
_cur_avail = None
_volfile = None
def __init__(self, parser, inf):
super().__init__()
self._open_extfile(parser, inf)
def _open_extfile(self, parser, inf):
super()._open_extfile(parser, inf)
self._volfile = self._inf.volume_file
self._fd = XFile(self._volfile, 0)
self._fd.seek(self._inf.header_offset, 0)
self._cur = self._parser._parse_header(self._fd)
self._cur_avail = self._cur.add_size
def _skip(self, cnt):
"""RAR Seek, skipping through rar files to get to correct position
"""
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
cnt -= self._cur_avail
self._remain -= self._cur_avail
self._cur_avail = 0
else:
self._fd.seek(cnt, 1)
self._cur_avail -= cnt
self._remain -= cnt
cnt = 0
def _read(self, cnt):
"""Read from potentially multi-volume archive."""
pos = self._fd.tell()
need = self._cur.data_offset + self._cur.add_size - self._cur_avail
if pos != need:
self._fd.seek(need, 0)
buf = []
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
data = self._fd.read(self._cur_avail)
else:
data = self._fd.read(cnt)
if not data:
break
# got some data
cnt -= len(data)
self._cur_avail -= len(data)
buf.append(data)
if len(buf) == 1:
return buf[0]
return b"".join(buf)
def _open_next(self):
"""Proceed to next volume."""
# is the file split over archives?
if (self._cur.flags & RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfile = self._parser._next_volname(self._volfile)
fd = open(self._volfile, "rb", 0)
self._fd = fd
sig = fd.read(len(self._parser._expect_sig))
if sig != self._parser._expect_sig:
raise BadRarFile("Invalid signature")
# loop until first file header
while True:
cur = self._parser._parse_header(fd)
if not cur:
raise BadRarFile("Unexpected EOF")
if cur.type in (RAR_BLOCK_MARK, RAR_BLOCK_MAIN):
if cur.add_size:
fd.seek(cur.add_size, 1)
continue
if cur.orig_filename != self._inf.orig_filename:
raise BadRarFile("Did not found file entry")
self._cur = cur
self._cur_avail = cur.add_size
return True
def readinto(self, buf):
"""Zero-copy read directly into buffer."""
got = 0
vbuf = memoryview(buf)
while got < len(buf):
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# length for next read
cnt = len(buf) - got
if cnt > self._cur_avail:
cnt = self._cur_avail
# read into temp view
res = self._fd.readinto(vbuf[got: got + cnt])
if not res:
break
self._md_context.update(vbuf[got: got + res])
self._cur_avail -= res
self._remain -= res
got += res
return got
| (parser, inf) |
11,302 | rarfile | __del__ | Hook delete to make sure tempfile is removed. | def __del__(self):
"""Hook delete to make sure tempfile is removed."""
self.close()
| (self) |
11,303 | rarfile | __init__ | null | def __init__(self, parser, inf):
super().__init__()
self._open_extfile(parser, inf)
| (self, parser, inf) |
11,304 | rarfile | _check | Check final CRC. | def _check(self):
"""Check final CRC."""
final = self._md_context.digest()
exp = self._inf._md_expect
if exp is None:
return
if final is None:
return
if self._returncode:
check_returncode(self._returncode, "", tool_setup().get_errmap())
if self._remain != 0:
raise BadRarFile("Failed the read enough data")
if final != exp:
raise BadRarFile("Corrupt file - CRC check failed: %s - exp=%r got=%r" % (
self._inf.filename, exp, final))
| (self) |
11,305 | rarfile | _open_extfile | null | def _open_extfile(self, parser, inf):
super()._open_extfile(parser, inf)
self._volfile = self._inf.volume_file
self._fd = XFile(self._volfile, 0)
self._fd.seek(self._inf.header_offset, 0)
self._cur = self._parser._parse_header(self._fd)
self._cur_avail = self._cur.add_size
| (self, parser, inf) |
11,306 | rarfile | _open_next | Proceed to next volume. | def _open_next(self):
"""Proceed to next volume."""
# is the file split over archives?
if (self._cur.flags & RAR_FILE_SPLIT_AFTER) == 0:
return False
if self._fd:
self._fd.close()
self._fd = None
# open next part
self._volfile = self._parser._next_volname(self._volfile)
fd = open(self._volfile, "rb", 0)
self._fd = fd
sig = fd.read(len(self._parser._expect_sig))
if sig != self._parser._expect_sig:
raise BadRarFile("Invalid signature")
# loop until first file header
while True:
cur = self._parser._parse_header(fd)
if not cur:
raise BadRarFile("Unexpected EOF")
if cur.type in (RAR_BLOCK_MARK, RAR_BLOCK_MAIN):
if cur.add_size:
fd.seek(cur.add_size, 1)
continue
if cur.orig_filename != self._inf.orig_filename:
raise BadRarFile("Did not found file entry")
self._cur = cur
self._cur_avail = cur.add_size
return True
| (self) |
11,307 | rarfile | _read | Read from potentially multi-volume archive. | def _read(self, cnt):
"""Read from potentially multi-volume archive."""
pos = self._fd.tell()
need = self._cur.data_offset + self._cur.add_size - self._cur_avail
if pos != need:
self._fd.seek(need, 0)
buf = []
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
data = self._fd.read(self._cur_avail)
else:
data = self._fd.read(cnt)
if not data:
break
# got some data
cnt -= len(data)
self._cur_avail -= len(data)
buf.append(data)
if len(buf) == 1:
return buf[0]
return b"".join(buf)
| (self, cnt) |
11,308 | rarfile | _skip | RAR Seek, skipping through rar files to get to correct position
| def _skip(self, cnt):
"""RAR Seek, skipping through rar files to get to correct position
"""
while cnt > 0:
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# fd is in read pos, do the read
if cnt > self._cur_avail:
cnt -= self._cur_avail
self._remain -= self._cur_avail
self._cur_avail = 0
else:
self._fd.seek(cnt, 1)
self._cur_avail -= cnt
self._remain -= cnt
cnt = 0
| (self, cnt) |
11,309 | rarfile | close | Close open resources. | def close(self):
"""Close open resources."""
super().close()
if self._fd:
self._fd.close()
self._fd = None
| (self) |
11,310 | rarfile | read | Read all or specified amount of data from archive entry. | def read(self, n=-1):
"""Read all or specified amount of data from archive entry."""
# sanitize count
if n is None or n < 0:
n = self._remain
elif n > self._remain:
n = self._remain
if n == 0:
return b""
buf = []
orig = n
while n > 0:
# actual read
data = self._read(n)
if not data:
break
buf.append(data)
self._md_context.update(data)
self._remain -= len(data)
n -= len(data)
data = b"".join(buf)
if n > 0:
raise BadRarFile("Failed the read enough data: req=%d got=%d" % (orig, len(data)))
# done?
if not data or self._remain == 0:
# self.close()
self._check()
return data
| (self, n=-1) |
11,311 | rarfile | readable | Returns True | def readable(self):
"""Returns True"""
return True
| (self) |
11,312 | rarfile | readall | Read all remaining data | def readall(self):
"""Read all remaining data"""
# avoid RawIOBase default impl
return self.read()
| (self) |
11,313 | rarfile | readinto | Zero-copy read directly into buffer. | def readinto(self, buf):
"""Zero-copy read directly into buffer."""
got = 0
vbuf = memoryview(buf)
while got < len(buf):
# next vol needed?
if self._cur_avail == 0:
if not self._open_next():
break
# length for next read
cnt = len(buf) - got
if cnt > self._cur_avail:
cnt = self._cur_avail
# read into temp view
res = self._fd.readinto(vbuf[got: got + cnt])
if not res:
break
self._md_context.update(vbuf[got: got + res])
self._cur_avail -= res
self._remain -= res
got += res
return got
| (self, buf) |
11,314 | rarfile | seek | Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compressed files its slow
- forward seeking happens by reading ahead,
backwards by re-opening and decompressing from the start.
| def seek(self, offset, whence=0):
"""Seek in data.
On uncompressed files, the seeking works by actual
seeks so it's fast. On compressed files its slow
- forward seeking happens by reading ahead,
backwards by re-opening and decompressing from the start.
"""
# disable crc check when seeking
if not self._seeking:
self._md_context = NoHashContext()
self._seeking = True
fsize = self._inf.file_size
cur_ofs = self.tell()
if whence == 0: # seek from beginning of file
new_ofs = offset
elif whence == 1: # seek from current position
new_ofs = cur_ofs + offset
elif whence == 2: # seek from end of file
new_ofs = fsize + offset
else:
raise ValueError("Invalid value for whence")
# sanity check
if new_ofs < 0:
new_ofs = 0
elif new_ofs > fsize:
new_ofs = fsize
# do the actual seek
if new_ofs >= cur_ofs:
self._skip(new_ofs - cur_ofs)
else:
# reopen and seek
self._open_extfile(self._parser, self._inf)
self._skip(new_ofs)
return self.tell()
| (self, offset, whence=0) |
11,315 | rarfile | seekable | Returns True.
Seeking is supported, although it's slow on compressed files.
| def seekable(self):
"""Returns True.
Seeking is supported, although it's slow on compressed files.
"""
return True
| (self) |
11,316 | rarfile | tell | Return current reading position in uncompressed data. | def tell(self):
"""Return current reading position in uncompressed data."""
return self._inf.file_size - self._remain
| (self) |
11,317 | rarfile | writable | Returns False.
Writing is not supported.
| def writable(self):
"""Returns False.
Writing is not supported.
"""
return False
| (self) |
11,318 | rarfile | Error | Base class for rarfile errors. | class Error(Exception):
"""Base class for rarfile errors."""
| null |
11,319 | rarfile | HeaderDecrypt | File-like object that decrypts from another file | class HeaderDecrypt:
"""File-like object that decrypts from another file"""
def __init__(self, f, key, iv):
self.f = f
self.ciph = AES_CBC_Decrypt(key, iv)
self.buf = b""
def tell(self):
"""Current file pos - works only on block boundaries."""
return self.f.tell()
def read(self, cnt=None):
"""Read and decrypt."""
if cnt > 8 * 1024:
raise BadRarFile("Bad count to header decrypt - wrong password?")
# consume old data
if cnt <= len(self.buf):
res = self.buf[:cnt]
self.buf = self.buf[cnt:]
return res
res = self.buf
self.buf = b""
cnt -= len(res)
# decrypt new data
blklen = 16
while cnt > 0:
enc = self.f.read(blklen)
if len(enc) < blklen:
break
dec = self.ciph.decrypt(enc)
if cnt >= len(dec):
res += dec
cnt -= len(dec)
else:
res += dec[:cnt]
self.buf = dec[cnt:]
cnt = 0
return res
| (f, key, iv) |
11,320 | rarfile | __init__ | null | def __init__(self, f, key, iv):
self.f = f
self.ciph = AES_CBC_Decrypt(key, iv)
self.buf = b""
| (self, f, key, iv) |
11,321 | rarfile | read | Read and decrypt. | def read(self, cnt=None):
"""Read and decrypt."""
if cnt > 8 * 1024:
raise BadRarFile("Bad count to header decrypt - wrong password?")
# consume old data
if cnt <= len(self.buf):
res = self.buf[:cnt]
self.buf = self.buf[cnt:]
return res
res = self.buf
self.buf = b""
cnt -= len(res)
# decrypt new data
blklen = 16
while cnt > 0:
enc = self.f.read(blklen)
if len(enc) < blklen:
break
dec = self.ciph.decrypt(enc)
if cnt >= len(dec):
res += dec
cnt -= len(dec)
else:
res += dec[:cnt]
self.buf = dec[cnt:]
cnt = 0
return res
| (self, cnt=None) |
11,322 | rarfile | tell | Current file pos - works only on block boundaries. | def tell(self):
"""Current file pos - works only on block boundaries."""
return self.f.tell()
| (self) |
11,323 | rarfile | NeedFirstVolume | Need to start from first volume.
Attributes:
current_volume
Volume number of current file or None if not known
| class NeedFirstVolume(Error):
"""Need to start from first volume.
Attributes:
current_volume
Volume number of current file or None if not known
"""
def __init__(self, msg, volume):
super().__init__(msg)
self.current_volume = volume
| (msg, volume) |
11,324 | rarfile | __init__ | null | def __init__(self, msg, volume):
super().__init__(msg)
self.current_volume = volume
| (self, msg, volume) |
11,325 | rarfile | NoCrypto | Cannot parse encrypted headers - no crypto available. | class NoCrypto(Error):
"""Cannot parse encrypted headers - no crypto available."""
| null |
11,326 | rarfile | NoHashContext | No-op hash function. | class NoHashContext:
"""No-op hash function."""
def __init__(self, data=None):
"""Initialize"""
def update(self, data):
"""Update data"""
def digest(self):
"""Final hash"""
def hexdigest(self):
"""Hexadecimal digest."""
| (data=None) |
11,327 | rarfile | __init__ | Initialize | def __init__(self, data=None):
"""Initialize"""
| (self, data=None) |
11,328 | rarfile | digest | Final hash | def digest(self):
"""Final hash"""
| (self) |
11,329 | rarfile | hexdigest | Hexadecimal digest. | def hexdigest(self):
"""Hexadecimal digest."""
| (self) |
11,330 | rarfile | update | Update data | def update(self, data):
"""Update data"""
| (self, data) |
11,331 | rarfile | NoRarEntry | File not found in RAR | class NoRarEntry(Error):
"""File not found in RAR"""
| null |
11,332 | rarfile | NotRarFile | The file is not RAR archive. | class NotRarFile(Error):
"""The file is not RAR archive."""
| null |
11,333 | rarfile | PasswordRequired | File requires password | class PasswordRequired(Error):
"""File requires password"""
| null |
11,401 | rarfile | PipeReader | Read data from pipe, handle tempfile cleanup. | class PipeReader(RarExtFile):
"""Read data from pipe, handle tempfile cleanup."""
def __init__(self, parser, inf, cmd, tempfile=None):
super().__init__()
self._cmd = cmd
self._proc = None
self._tempfile = tempfile
self._open_extfile(parser, inf)
def _close_proc(self):
if not self._proc:
return
for f in (self._proc.stdout, self._proc.stderr, self._proc.stdin):
if f:
f.close()
self._proc.wait()
self._returncode = self._proc.returncode
self._proc = None
def _open_extfile(self, parser, inf):
super()._open_extfile(parser, inf)
# stop old process
self._close_proc()
# launch new process
self._returncode = 0
self._proc = custom_popen(self._cmd)
self._fd = self._proc.stdout
def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try looping
buf = [data]
cnt -= len(data)
while cnt > 0:
data = self._fd.read(cnt)
if not data:
break
cnt -= len(data)
buf.append(data)
return b"".join(buf)
def close(self):
"""Close open resources."""
self._close_proc()
super().close()
if self._tempfile:
try:
os.unlink(self._tempfile)
except OSError:
pass
self._tempfile = None
def readinto(self, buf):
"""Zero-copy read directly into buffer."""
cnt = len(buf)
if cnt > self._remain:
cnt = self._remain
vbuf = memoryview(buf)
res = got = 0
while got < cnt:
res = self._fd.readinto(vbuf[got: cnt])
if not res:
break
self._md_context.update(vbuf[got: got + res])
self._remain -= res
got += res
return got
| (parser, inf, cmd, tempfile=None) |
11,403 | rarfile | __init__ | null | def __init__(self, parser, inf, cmd, tempfile=None):
super().__init__()
self._cmd = cmd
self._proc = None
self._tempfile = tempfile
self._open_extfile(parser, inf)
| (self, parser, inf, cmd, tempfile=None) |
11,405 | rarfile | _close_proc | null | def _close_proc(self):
if not self._proc:
return
for f in (self._proc.stdout, self._proc.stderr, self._proc.stdin):
if f:
f.close()
self._proc.wait()
self._returncode = self._proc.returncode
self._proc = None
| (self) |
11,406 | rarfile | _open_extfile | null | def _open_extfile(self, parser, inf):
super()._open_extfile(parser, inf)
# stop old process
self._close_proc()
# launch new process
self._returncode = 0
self._proc = custom_popen(self._cmd)
self._fd = self._proc.stdout
| (self, parser, inf) |
11,407 | rarfile | _read | Read from pipe. | def _read(self, cnt):
"""Read from pipe."""
# normal read is usually enough
data = self._fd.read(cnt)
if len(data) == cnt or not data:
return data
# short read, try looping
buf = [data]
cnt -= len(data)
while cnt > 0:
data = self._fd.read(cnt)
if not data:
break
cnt -= len(data)
buf.append(data)
return b"".join(buf)
| (self, cnt) |
11,408 | rarfile | _skip | Read and discard data | def _skip(self, cnt):
"""Read and discard data"""
empty_read(self, cnt, BSIZE)
| (self, cnt) |
11,409 | rarfile | close | Close open resources. | def close(self):
"""Close open resources."""
self._close_proc()
super().close()
if self._tempfile:
try:
os.unlink(self._tempfile)
except OSError:
pass
self._tempfile = None
| (self) |
11,413 | rarfile | readinto | Zero-copy read directly into buffer. | def readinto(self, buf):
"""Zero-copy read directly into buffer."""
cnt = len(buf)
if cnt > self._remain:
cnt = self._remain
vbuf = memoryview(buf)
res = got = 0
while got < cnt:
res = self._fd.readinto(vbuf[got: cnt])
if not res:
break
self._md_context.update(vbuf[got: got + res])
self._remain -= res
got += res
return got
| (self, buf) |
11,418 | subprocess | Popen | Execute a child program in a new process.
For a complete description of the arguments see the Python documentation.
Arguments:
args: A string, or a sequence of program arguments.
bufsize: supplied as the buffering argument to the open() function when
creating the stdin/stdout/stderr pipe file objects
executable: A replacement program to execute.
stdin, stdout and stderr: These specify the executed programs' standard
input, standard output and standard error file handles, respectively.
preexec_fn: (POSIX only) An object to be called in the child process
just before the child is executed.
close_fds: Controls closing or inheriting of file descriptors.
shell: If true, the command will be executed through the shell.
cwd: Sets the current directory before the child is executed.
env: Defines the environment variables for the new process.
text: If true, decode stdin, stdout and stderr using the given encoding
(if set) or the system default otherwise.
universal_newlines: Alias of text, provided for backwards compatibility.
startupinfo and creationflags (Windows only)
restore_signals (POSIX only)
start_new_session (POSIX only)
group (POSIX only)
extra_groups (POSIX only)
user (POSIX only)
umask (POSIX only)
pass_fds (POSIX only)
encoding and errors: Text mode encoding and error handling to use for
file objects stdin, stdout and stderr.
Attributes:
stdin, stdout, stderr, pid, returncode
| class Popen:
""" Execute a child program in a new process.
For a complete description of the arguments see the Python documentation.
Arguments:
args: A string, or a sequence of program arguments.
bufsize: supplied as the buffering argument to the open() function when
creating the stdin/stdout/stderr pipe file objects
executable: A replacement program to execute.
stdin, stdout and stderr: These specify the executed programs' standard
input, standard output and standard error file handles, respectively.
preexec_fn: (POSIX only) An object to be called in the child process
just before the child is executed.
close_fds: Controls closing or inheriting of file descriptors.
shell: If true, the command will be executed through the shell.
cwd: Sets the current directory before the child is executed.
env: Defines the environment variables for the new process.
text: If true, decode stdin, stdout and stderr using the given encoding
(if set) or the system default otherwise.
universal_newlines: Alias of text, provided for backwards compatibility.
startupinfo and creationflags (Windows only)
restore_signals (POSIX only)
start_new_session (POSIX only)
group (POSIX only)
extra_groups (POSIX only)
user (POSIX only)
umask (POSIX only)
pass_fds (POSIX only)
encoding and errors: Text mode encoding and error handling to use for
file objects stdin, stdout and stderr.
Attributes:
stdin, stdout, stderr, pid, returncode
"""
_child_created = False # Set here since __del__ checks it
def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, user=None, group=None, extra_groups=None,
encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
"""Create new Popen instance."""
_cleanup()
# Held while anything is calling waitpid before returncode has been
# updated to prevent clobbering returncode if wait() or poll() are
# called from multiple threads at once. After acquiring the lock,
# code must re-check self.returncode to see if another thread just
# finished a waitpid() call.
self._waitpid_lock = threading.Lock()
self._input = None
self._communication_started = False
if bufsize is None:
bufsize = -1 # Restore default
if not isinstance(bufsize, int):
raise TypeError("bufsize must be an integer")
if pipesize is None:
pipesize = -1 # Restore default
if not isinstance(pipesize, int):
raise TypeError("pipesize must be an integer")
if _mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
else:
# POSIX
if pass_fds and not close_fds:
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
self.args = args
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.encoding = encoding
self.errors = errors
self.pipesize = pipesize
# Validate the combinations of text and universal_newlines
if (text is not None and universal_newlines is not None
and bool(universal_newlines) != bool(text)):
raise SubprocessError('Cannot disambiguate when both text '
'and universal_newlines are supplied but '
'different. Pass one or the other.')
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are -1 when not using PIPEs. The child objects are -1
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if _mswindows:
if p2cwrite != -1:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread != -1:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread != -1:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
self.text_mode = encoding or errors or text or universal_newlines
# PEP 597: We suppress the EncodingWarning in subprocess module
# for now (at Python 3.10), because we focus on files for now.
# This will be changed to encoding = io.text_encoding(encoding)
# in the future.
if self.text_mode and encoding is None:
self.encoding = encoding = "locale"
# How long to resume waiting on a child after the first ^C.
# There is no right value for this. The purpose is to be polite
# yet remain good for interactive users trying to exit a tool.
self._sigint_wait_secs = 0.25 # 1/xkcd221.getRandomNumber()
self._closed_child_pipe_fds = False
if self.text_mode:
if bufsize == 1:
line_buffering = True
# Use the default buffer size for the underlying binary streams
# since they don't support line buffering.
bufsize = -1
else:
line_buffering = False
gid = None
if group is not None:
if not hasattr(os, 'setregid'):
raise ValueError("The 'group' parameter is not supported on the "
"current platform")
elif isinstance(group, str):
try:
import grp
except ImportError:
raise ValueError("The group parameter cannot be a string "
"on systems without the grp module")
gid = grp.getgrnam(group).gr_gid
elif isinstance(group, int):
gid = group
else:
raise TypeError("Group must be a string or an integer, not {}"
.format(type(group)))
if gid < 0:
raise ValueError(f"Group ID cannot be negative, got {gid}")
gids = None
if extra_groups is not None:
if not hasattr(os, 'setgroups'):
raise ValueError("The 'extra_groups' parameter is not "
"supported on the current platform")
elif isinstance(extra_groups, str):
raise ValueError("Groups must be a list, not a string")
gids = []
for extra_group in extra_groups:
if isinstance(extra_group, str):
try:
import grp
except ImportError:
raise ValueError("Items in extra_groups cannot be "
"strings on systems without the "
"grp module")
gids.append(grp.getgrnam(extra_group).gr_gid)
elif isinstance(extra_group, int):
gids.append(extra_group)
else:
raise TypeError("Items in extra_groups must be a string "
"or integer, not {}"
.format(type(extra_group)))
# make sure that the gids are all positive here so we can do less
# checking in the C code
for gid_check in gids:
if gid_check < 0:
raise ValueError(f"Group ID cannot be negative, got {gid_check}")
uid = None
if user is not None:
if not hasattr(os, 'setreuid'):
raise ValueError("The 'user' parameter is not supported on "
"the current platform")
elif isinstance(user, str):
try:
import pwd
except ImportError:
raise ValueError("The user parameter cannot be a string "
"on systems without the pwd module")
uid = pwd.getpwnam(user).pw_uid
elif isinstance(user, int):
uid = user
else:
raise TypeError("User must be a string or an integer")
if uid < 0:
raise ValueError(f"User ID cannot be negative, got {uid}")
try:
if p2cwrite != -1:
self.stdin = io.open(p2cwrite, 'wb', bufsize)
if self.text_mode:
self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
line_buffering=line_buffering,
encoding=encoding, errors=errors)
if c2pread != -1:
self.stdout = io.open(c2pread, 'rb', bufsize)
if self.text_mode:
self.stdout = io.TextIOWrapper(self.stdout,
encoding=encoding, errors=errors)
if errread != -1:
self.stderr = io.open(errread, 'rb', bufsize)
if self.text_mode:
self.stderr = io.TextIOWrapper(self.stderr,
encoding=encoding, errors=errors)
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals,
gid, gids, uid, umask,
start_new_session)
except:
# Cleanup if the child failed starting.
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except OSError:
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
if _mswindows and isinstance(fd, Handle):
fd.Close()
else:
os.close(fd)
except OSError:
pass
raise
def __repr__(self):
obj_repr = (
f"<{self.__class__.__name__}: "
f"returncode: {self.returncode} args: {self.args!r}>"
)
if len(obj_repr) > 80:
obj_repr = obj_repr[:76] + "...>"
return obj_repr
__class_getitem__ = classmethod(types.GenericAlias)
@property
def universal_newlines(self):
# universal_newlines as retained as an alias of text_mode for API
# compatibility. bpo-31756
return self.text_mode
@universal_newlines.setter
def universal_newlines(self, universal_newlines):
self.text_mode = bool(universal_newlines)
def _translate_newlines(self, data, encoding, errors):
data = data.decode(encoding, errors)
return data.replace("\r\n", "\n").replace("\r", "\n")
def __enter__(self):
return self
def __exit__(self, exc_type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
try: # Flushing a BufferedWriter may raise an error
if self.stdin:
self.stdin.close()
finally:
if exc_type == KeyboardInterrupt:
# https://bugs.python.org/issue25942
# In the case of a KeyboardInterrupt we assume the SIGINT
# was also already sent to our child processes. We can't
# block indefinitely as that is not user friendly.
# If we have not already waited a brief amount of time in
# an interrupted .wait() or .communicate() call, do so here
# for consistency.
if self._sigint_wait_secs > 0:
try:
self._wait(timeout=self._sigint_wait_secs)
except TimeoutExpired:
pass
self._sigint_wait_secs = 0 # Note that this has been done.
return # resume the KeyboardInterrupt
# Wait for the process to terminate, to avoid zombies.
self.wait()
def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
if not self._child_created:
# We didn't get to successfully create a child process.
return
if self.returncode is None:
# Not reading subprocess exit status creates a zombie process which
# is only destroyed at the parent python process exit
_warn("subprocess %s is still running" % self.pid,
ResourceWarning, source=self)
# In case the child hasn't been waited on, check if it's done.
self._internal_poll(_deadstate=_maxsize)
if self.returncode is None and _active is not None:
# Child is still running, keep us alive until we can wait on it.
_active.append(self)
def _get_devnull(self):
if not hasattr(self, '_devnull'):
self._devnull = os.open(os.devnull, os.O_RDWR)
return self._devnull
def _stdin_write(self, input):
if input:
try:
self.stdin.write(input)
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
# bpo-19612, bpo-30418: On Windows, stdin.write() fails
# with EINVAL if the child process exited or if the child
# process is still running but closed the pipe.
pass
else:
raise
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
pass
else:
raise
def communicate(self, input=None, timeout=None):
"""Interact with process: Send data to stdin and close it.
Read data from stdout and stderr, until end-of-file is
reached. Wait for process to terminate.
The optional "input" argument should be data to be sent to the
child process, or None, if no data should be sent to the child.
communicate() returns a tuple (stdout, stderr).
By default, all communication is in bytes, and therefore any
"input" should be bytes, and the (stdout, stderr) will be bytes.
If in text mode (indicated by self.text_mode), any "input" should
be a string, and (stdout, stderr) will be strings decoded
according to locale encoding, or by "encoding" if set. Text mode
is triggered by setting any of text, encoding, errors or
universal_newlines.
"""
if self._communication_started and input:
raise ValueError("Cannot send input after starting communication")
# Optimization: If we are not worried about timeouts, we haven't
# started communicating, and we have one or zero pipes, using select()
# or threads is unnecessary.
if (timeout is None and not self._communication_started and
[self.stdin, self.stdout, self.stderr].count(None) >= 2):
stdout = None
stderr = None
if self.stdin:
self._stdin_write(input)
elif self.stdout:
stdout = self.stdout.read()
self.stdout.close()
elif self.stderr:
stderr = self.stderr.read()
self.stderr.close()
self.wait()
else:
if timeout is not None:
endtime = _time() + timeout
else:
endtime = None
try:
stdout, stderr = self._communicate(input, endtime, timeout)
except KeyboardInterrupt:
# https://bugs.python.org/issue25942
# See the detailed comment in .wait().
if timeout is not None:
sigint_timeout = min(self._sigint_wait_secs,
self._remaining_time(endtime))
else:
sigint_timeout = self._sigint_wait_secs
self._sigint_wait_secs = 0 # nothing else should wait.
try:
self._wait(timeout=sigint_timeout)
except TimeoutExpired:
pass
raise # resume the KeyboardInterrupt
finally:
self._communication_started = True
sts = self.wait(timeout=self._remaining_time(endtime))
return (stdout, stderr)
def poll(self):
"""Check if child process has terminated. Set and return returncode
attribute."""
return self._internal_poll()
def _remaining_time(self, endtime):
"""Convenience for _communicate when computing timeouts."""
if endtime is None:
return None
else:
return endtime - _time()
def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq,
skip_check_and_raise=False):
"""Convenience for checking if a timeout has expired."""
if endtime is None:
return
if skip_check_and_raise or _time() > endtime:
raise TimeoutExpired(
self.args, orig_timeout,
output=b''.join(stdout_seq) if stdout_seq else None,
stderr=b''.join(stderr_seq) if stderr_seq else None)
def wait(self, timeout=None):
"""Wait for child process to terminate; returns self.returncode."""
if timeout is not None:
endtime = _time() + timeout
try:
return self._wait(timeout=timeout)
except KeyboardInterrupt:
# https://bugs.python.org/issue25942
# The first keyboard interrupt waits briefly for the child to
# exit under the common assumption that it also received the ^C
# generated SIGINT and will exit rapidly.
if timeout is not None:
sigint_timeout = min(self._sigint_wait_secs,
self._remaining_time(endtime))
else:
sigint_timeout = self._sigint_wait_secs
self._sigint_wait_secs = 0 # nothing else should wait.
try:
self._wait(timeout=sigint_timeout)
except TimeoutExpired:
pass
raise # resume the KeyboardInterrupt
def _close_pipe_fds(self,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
# self._devnull is not always defined.
devnull_fd = getattr(self, '_devnull', None)
with contextlib.ExitStack() as stack:
if _mswindows:
if p2cread != -1:
stack.callback(p2cread.Close)
if c2pwrite != -1:
stack.callback(c2pwrite.Close)
if errwrite != -1:
stack.callback(errwrite.Close)
else:
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
stack.callback(os.close, p2cread)
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
stack.callback(os.close, c2pwrite)
if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
stack.callback(os.close, errwrite)
if devnull_fd is not None:
stack.callback(os.close, devnull_fd)
# Prevent a double close of these handles/fds from __init__ on error.
self._closed_child_pipe_fds = True
if _mswindows:
#
# Windows methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
if stdin is None and stdout is None and stderr is None:
return (-1, -1, -1, -1, -1, -1)
p2cread, p2cwrite = -1, -1
c2pread, c2pwrite = -1, -1
errread, errwrite = -1, -1
if stdin is None:
p2cread = _winapi.GetStdHandle(_winapi.STD_INPUT_HANDLE)
if p2cread is None:
p2cread, _ = _winapi.CreatePipe(None, 0)
p2cread = Handle(p2cread)
_winapi.CloseHandle(_)
elif stdin == PIPE:
p2cread, p2cwrite = _winapi.CreatePipe(None, 0)
p2cread, p2cwrite = Handle(p2cread), Handle(p2cwrite)
elif stdin == DEVNULL:
p2cread = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdin, int):
p2cread = msvcrt.get_osfhandle(stdin)
else:
# Assuming file-like object
p2cread = msvcrt.get_osfhandle(stdin.fileno())
p2cread = self._make_inheritable(p2cread)
if stdout is None:
c2pwrite = _winapi.GetStdHandle(_winapi.STD_OUTPUT_HANDLE)
if c2pwrite is None:
_, c2pwrite = _winapi.CreatePipe(None, 0)
c2pwrite = Handle(c2pwrite)
_winapi.CloseHandle(_)
elif stdout == PIPE:
c2pread, c2pwrite = _winapi.CreatePipe(None, 0)
c2pread, c2pwrite = Handle(c2pread), Handle(c2pwrite)
elif stdout == DEVNULL:
c2pwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stdout, int):
c2pwrite = msvcrt.get_osfhandle(stdout)
else:
# Assuming file-like object
c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
c2pwrite = self._make_inheritable(c2pwrite)
if stderr is None:
errwrite = _winapi.GetStdHandle(_winapi.STD_ERROR_HANDLE)
if errwrite is None:
_, errwrite = _winapi.CreatePipe(None, 0)
errwrite = Handle(errwrite)
_winapi.CloseHandle(_)
elif stderr == PIPE:
errread, errwrite = _winapi.CreatePipe(None, 0)
errread, errwrite = Handle(errread), Handle(errwrite)
elif stderr == STDOUT:
errwrite = c2pwrite
elif stderr == DEVNULL:
errwrite = msvcrt.get_osfhandle(self._get_devnull())
elif isinstance(stderr, int):
errwrite = msvcrt.get_osfhandle(stderr)
else:
# Assuming file-like object
errwrite = msvcrt.get_osfhandle(stderr.fileno())
errwrite = self._make_inheritable(errwrite)
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _make_inheritable(self, handle):
"""Return a duplicate of handle, which is inheritable"""
h = _winapi.DuplicateHandle(
_winapi.GetCurrentProcess(), handle,
_winapi.GetCurrentProcess(), 0, 1,
_winapi.DUPLICATE_SAME_ACCESS)
return Handle(h)
def _filter_handle_list(self, handle_list):
"""Filter out console handles that can't be used
in lpAttributeList["handle_list"] and make sure the list
isn't empty. This also removes duplicate handles."""
# An handle with it's lowest two bits set might be a special console
# handle that if passed in lpAttributeList["handle_list"], will
# cause it to fail.
return list({handle for handle in handle_list
if handle & 0x3 != 0x3
or _winapi.GetFileType(handle) !=
_winapi.FILE_TYPE_CHAR})
def _execute_child(self, args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
unused_restore_signals,
unused_gid, unused_gids, unused_uid,
unused_umask,
unused_start_new_session):
"""Execute program (MS Windows version)"""
assert not pass_fds, "pass_fds not supported on Windows."
if isinstance(args, str):
pass
elif isinstance(args, bytes):
if shell:
raise TypeError('bytes args is not allowed on Windows')
args = list2cmdline([args])
elif isinstance(args, os.PathLike):
if shell:
raise TypeError('path-like args is not allowed when '
'shell is true')
args = list2cmdline([args])
else:
args = list2cmdline(args)
if executable is not None:
executable = os.fsdecode(executable)
# Process startup details
if startupinfo is None:
startupinfo = STARTUPINFO()
else:
# bpo-34044: Copy STARTUPINFO since it is modified above,
# so the caller can reuse it multiple times.
startupinfo = startupinfo.copy()
use_std_handles = -1 not in (p2cread, c2pwrite, errwrite)
if use_std_handles:
startupinfo.dwFlags |= _winapi.STARTF_USESTDHANDLES
startupinfo.hStdInput = p2cread
startupinfo.hStdOutput = c2pwrite
startupinfo.hStdError = errwrite
attribute_list = startupinfo.lpAttributeList
have_handle_list = bool(attribute_list and
"handle_list" in attribute_list and
attribute_list["handle_list"])
# If we were given an handle_list or need to create one
if have_handle_list or (use_std_handles and close_fds):
if attribute_list is None:
attribute_list = startupinfo.lpAttributeList = {}
handle_list = attribute_list["handle_list"] = \
list(attribute_list.get("handle_list", []))
if use_std_handles:
handle_list += [int(p2cread), int(c2pwrite), int(errwrite)]
handle_list[:] = self._filter_handle_list(handle_list)
if handle_list:
if not close_fds:
warnings.warn("startupinfo.lpAttributeList['handle_list'] "
"overriding close_fds", RuntimeWarning)
# When using the handle_list we always request to inherit
# handles but the only handles that will be inherited are
# the ones in the handle_list
close_fds = False
if shell:
startupinfo.dwFlags |= _winapi.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = _winapi.SW_HIDE
if not executable:
# gh-101283: without a fully-qualified path, before Windows
# checks the system directories, it first looks in the
# application directory, and also the current directory if
# NeedCurrentDirectoryForExePathW(ExeName) is true, so try
# to avoid executing unqualified "cmd.exe".
comspec = os.environ.get('ComSpec')
if not comspec:
system_root = os.environ.get('SystemRoot', '')
comspec = os.path.join(system_root, 'System32', 'cmd.exe')
if not os.path.isabs(comspec):
raise FileNotFoundError('shell not found: neither %ComSpec% nor %SystemRoot% is set')
if os.path.isabs(comspec):
executable = comspec
else:
comspec = executable
args = '{} /c "{}"'.format (comspec, args)
if cwd is not None:
cwd = os.fsdecode(cwd)
sys.audit("subprocess.Popen", executable, args, cwd, env)
# Start the process
try:
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
# no special security
None, None,
int(not close_fds),
creationflags,
env,
cwd,
startupinfo)
finally:
# Child is launched. Close the parent's copy of those pipe
# handles that only the child should have open. You need
# to make sure that no handles to the write end of the
# output pipe are maintained in this process or else the
# pipe will not close when the child process exits and the
# ReadFile will hang.
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
# Retain the process handle, but close the thread handle
self._child_created = True
self._handle = Handle(hp)
self.pid = pid
_winapi.CloseHandle(ht)
def _internal_poll(self, _deadstate=None,
_WaitForSingleObject=_winapi.WaitForSingleObject,
_WAIT_OBJECT_0=_winapi.WAIT_OBJECT_0,
_GetExitCodeProcess=_winapi.GetExitCodeProcess):
"""Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it can only refer to objects
in its local scope.
"""
if self.returncode is None:
if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
self.returncode = _GetExitCodeProcess(self._handle)
return self.returncode
def _wait(self, timeout):
"""Internal implementation of wait() on Windows."""
if timeout is None:
timeout_millis = _winapi.INFINITE
else:
timeout_millis = int(timeout * 1000)
if self.returncode is None:
# API note: Returns immediately if timeout_millis == 0.
result = _winapi.WaitForSingleObject(self._handle,
timeout_millis)
if result == _winapi.WAIT_TIMEOUT:
raise TimeoutExpired(self.args, timeout)
self.returncode = _winapi.GetExitCodeProcess(self._handle)
return self.returncode
def _readerthread(self, fh, buffer):
buffer.append(fh.read())
fh.close()
def _communicate(self, input, endtime, orig_timeout):
# Start reader threads feeding into a list hanging off of this
# object, unless they've already been started.
if self.stdout and not hasattr(self, "_stdout_buff"):
self._stdout_buff = []
self.stdout_thread = \
threading.Thread(target=self._readerthread,
args=(self.stdout, self._stdout_buff))
self.stdout_thread.daemon = True
self.stdout_thread.start()
if self.stderr and not hasattr(self, "_stderr_buff"):
self._stderr_buff = []
self.stderr_thread = \
threading.Thread(target=self._readerthread,
args=(self.stderr, self._stderr_buff))
self.stderr_thread.daemon = True
self.stderr_thread.start()
if self.stdin:
self._stdin_write(input)
# Wait for the reader threads, or time out. If we time out, the
# threads remain reading and the fds left open in case the user
# calls communicate again.
if self.stdout is not None:
self.stdout_thread.join(self._remaining_time(endtime))
if self.stdout_thread.is_alive():
raise TimeoutExpired(self.args, orig_timeout)
if self.stderr is not None:
self.stderr_thread.join(self._remaining_time(endtime))
if self.stderr_thread.is_alive():
raise TimeoutExpired(self.args, orig_timeout)
# Collect the output from and close both pipes, now that we know
# both have been read successfully.
stdout = None
stderr = None
if self.stdout:
stdout = self._stdout_buff
self.stdout.close()
if self.stderr:
stderr = self._stderr_buff
self.stderr.close()
# All data exchanged. Translate lists into strings.
stdout = stdout[0] if stdout else None
stderr = stderr[0] if stderr else None
return (stdout, stderr)
def send_signal(self, sig):
"""Send a signal to the process."""
# Don't signal a process that we know has already died.
if self.returncode is not None:
return
if sig == signal.SIGTERM:
self.terminate()
elif sig == signal.CTRL_C_EVENT:
os.kill(self.pid, signal.CTRL_C_EVENT)
elif sig == signal.CTRL_BREAK_EVENT:
os.kill(self.pid, signal.CTRL_BREAK_EVENT)
else:
raise ValueError("Unsupported signal: {}".format(sig))
def terminate(self):
"""Terminates the process."""
# Don't terminate a process that we know has already died.
if self.returncode is not None:
return
try:
_winapi.TerminateProcess(self._handle, 1)
except PermissionError:
# ERROR_ACCESS_DENIED (winerror 5) is received when the
# process already died.
rc = _winapi.GetExitCodeProcess(self._handle)
if rc == _winapi.STILL_ACTIVE:
raise
self.returncode = rc
kill = terminate
else:
#
# POSIX methods
#
def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
p2cread, p2cwrite = -1, -1
c2pread, c2pwrite = -1, -1
errread, errwrite = -1, -1
if stdin is None:
pass
elif stdin == PIPE:
p2cread, p2cwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdin == DEVNULL:
p2cread = self._get_devnull()
elif isinstance(stdin, int):
p2cread = stdin
else:
# Assuming file-like object
p2cread = stdin.fileno()
if stdout is None:
pass
elif stdout == PIPE:
c2pread, c2pwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdout == DEVNULL:
c2pwrite = self._get_devnull()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
# Assuming file-like object
c2pwrite = stdout.fileno()
if stderr is None:
pass
elif stderr == PIPE:
errread, errwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stderr == STDOUT:
if c2pwrite != -1:
errwrite = c2pwrite
else: # child's stdout is not set, use parent's stdout
errwrite = sys.__stdout__.fileno()
elif stderr == DEVNULL:
errwrite = self._get_devnull()
elif isinstance(stderr, int):
errwrite = stderr
else:
# Assuming file-like object
errwrite = stderr.fileno()
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
def _posix_spawn(self, args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
"""Execute program using os.posix_spawn()."""
if env is None:
env = os.environ
kwargs = {}
if restore_signals:
# See _Py_RestoreSignals() in Python/pylifecycle.c
sigset = []
for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
signum = getattr(signal, signame, None)
if signum is not None:
sigset.append(signum)
kwargs['setsigdef'] = sigset
file_actions = []
for fd in (p2cwrite, c2pread, errread):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_CLOSE, fd))
for fd, fd2 in (
(p2cread, 0),
(c2pwrite, 1),
(errwrite, 2),
):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_DUP2, fd, fd2))
if file_actions:
kwargs['file_actions'] = file_actions
self.pid = os.posix_spawn(executable, args, env, **kwargs)
self._child_created = True
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
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,
gid, gids, uid, umask,
start_new_session):
"""Execute program (POSIX version)"""
if isinstance(args, (str, bytes)):
args = [args]
elif isinstance(args, os.PathLike):
if shell:
raise TypeError('path-like args is not allowed when '
'shell is true')
args = [args]
else:
args = list(args)
if shell:
# On Android the default shell is at '/system/bin/sh'.
unix_shell = ('/system/bin/sh' if
hasattr(sys, 'getandroidapilevel') else '/bin/sh')
args = [unix_shell, "-c"] + args
if executable:
args[0] = executable
if executable is None:
executable = args[0]
sys.audit("subprocess.Popen", executable, args, cwd, env)
if (_USE_POSIX_SPAWN
and os.path.dirname(executable)
and preexec_fn is None
and not close_fds
and not pass_fds
and cwd is None
and (p2cread == -1 or p2cread > 2)
and (c2pwrite == -1 or c2pwrite > 2)
and (errwrite == -1 or errwrite > 2)
and not start_new_session
and gid is None
and gids is None
and uid is None
and umask < 0):
self._posix_spawn(args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
return
orig_executable = executable
# For transferring possible exec failure from child to parent.
# Data format: "exception name:hex errno:description"
# Pickle is not used; it is complex and involves memory allocation.
errpipe_read, errpipe_write = os.pipe()
# errpipe_write must not be in the standard io 0, 1, or 2 fd range.
low_fds_to_close = []
while errpipe_write < 3:
low_fds_to_close.append(errpipe_write)
errpipe_write = os.dup(errpipe_write)
for low_fd in low_fds_to_close:
os.close(low_fd)
try:
try:
# We must avoid complex work that could involve
# malloc or free in the child process to avoid
# potential deadlocks, thus we do all this here.
# and pass it to fork_exec()
if env is not None:
env_list = []
for k, v in env.items():
k = os.fsencode(k)
if b'=' in k:
raise ValueError("illegal environment variable name")
env_list.append(k + b'=' + os.fsencode(v))
else:
env_list = None # Use execv instead of execve.
executable = os.fsencode(executable)
if os.path.dirname(executable):
executable_list = (executable,)
else:
# This matches the behavior of os._execvpe().
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, tuple(sorted(map(int, fds_to_keep))),
cwd, env_list,
p2cread, p2cwrite, c2pread, c2pwrite,
errread, errwrite,
errpipe_read, errpipe_write,
restore_signals, start_new_session,
gid, gids, uid, umask,
preexec_fn)
self._child_created = True
finally:
# be sure the FD is closed no matter what
os.close(errpipe_write)
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
# Wait for exec to fail or succeed; possibly raising an
# exception (limited in size)
errpipe_data = bytearray()
while True:
part = os.read(errpipe_read, 50000)
errpipe_data += part
if not part or len(errpipe_data) > 50000:
break
finally:
# be sure the FD is closed no matter what
os.close(errpipe_read)
if errpipe_data:
try:
pid, sts = os.waitpid(self.pid, 0)
if pid == self.pid:
self._handle_exitstatus(sts)
else:
self.returncode = sys.maxsize
except ChildProcessError:
pass
try:
exception_name, hex_errno, err_msg = (
errpipe_data.split(b':', 2))
# The encoding here should match the encoding
# written in by the subprocess implementations
# like _posixsubprocess
err_msg = err_msg.decode()
except ValueError:
exception_name = b'SubprocessError'
hex_errno = b'0'
err_msg = 'Bad exception data from child: {!r}'.format(
bytes(errpipe_data))
child_exception_type = getattr(
builtins, exception_name.decode('ascii'),
SubprocessError)
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 = ""
# The error must be from chdir(cwd).
err_filename = cwd
else:
err_filename = orig_executable
if errno_num != 0:
err_msg = os.strerror(errno_num)
raise child_exception_type(errno_num, err_msg, err_filename)
raise child_exception_type(err_msg)
def _handle_exitstatus(self, sts,
waitstatus_to_exitcode=os.waitstatus_to_exitcode,
_WIFSTOPPED=os.WIFSTOPPED,
_WSTOPSIG=os.WSTOPSIG):
"""All callers to this function MUST hold self._waitpid_lock."""
# This method is called (indirectly) by __del__, so it cannot
# refer to anything outside of its local scope.
if _WIFSTOPPED(sts):
self.returncode = -_WSTOPSIG(sts)
else:
self.returncode = waitstatus_to_exitcode(sts)
def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
_WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
"""Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it cannot reference anything
outside of the local scope (nor can any methods it calls).
"""
if self.returncode is None:
if not self._waitpid_lock.acquire(False):
# Something else is busy calling waitpid. Don't allow two
# at once. We know nothing yet.
return None
try:
if self.returncode is not None:
return self.returncode # Another thread waited.
pid, sts = _waitpid(self.pid, _WNOHANG)
if pid == self.pid:
self._handle_exitstatus(sts)
except OSError as e:
if _deadstate is not None:
self.returncode = _deadstate
elif e.errno == _ECHILD:
# This happens if SIGCLD is set to be ignored or
# waiting for child processes has otherwise been
# disabled for our process. This child is dead, we
# can't get the status.
# http://bugs.python.org/issue15756
self.returncode = 0
finally:
self._waitpid_lock.release()
return self.returncode
def _try_wait(self, wait_flags):
"""All callers to this function MUST hold self._waitpid_lock."""
try:
(pid, sts) = os.waitpid(self.pid, wait_flags)
except ChildProcessError:
# This happens if SIGCLD is set to be ignored or waiting
# for child processes has otherwise been disabled for our
# process. This child is dead, we can't get the status.
pid = self.pid
sts = 0
return (pid, sts)
def _wait(self, timeout):
"""Internal implementation of wait() on POSIX."""
if self.returncode is not None:
return self.returncode
if timeout is not None:
endtime = _time() + timeout
# Enter a busy loop if we have a timeout. This busy loop was
# cribbed from Lib/threading.py in Thread.wait() at r71065.
delay = 0.0005 # 500 us -> initial delay of 1 ms
while True:
if self._waitpid_lock.acquire(False):
try:
if self.returncode is not None:
break # Another thread waited.
(pid, sts) = self._try_wait(os.WNOHANG)
assert pid == self.pid or pid == 0
if pid == self.pid:
self._handle_exitstatus(sts)
break
finally:
self._waitpid_lock.release()
remaining = self._remaining_time(endtime)
if remaining <= 0:
raise TimeoutExpired(self.args, timeout)
delay = min(delay * 2, remaining, .05)
time.sleep(delay)
else:
while self.returncode is None:
with self._waitpid_lock:
if self.returncode is not None:
break # Another thread waited.
(pid, sts) = self._try_wait(0)
# Check the pid and loop as waitpid has been known to
# return 0 even without WNOHANG in odd situations.
# http://bugs.python.org/issue14396.
if pid == self.pid:
self._handle_exitstatus(sts)
return self.returncode
def _communicate(self, input, endtime, orig_timeout):
if self.stdin and not self._communication_started:
# Flush stdio buffer. This might block, if the user has
# been writing to .stdin in an uncontrolled fashion.
try:
self.stdin.flush()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
if not input:
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
stdout = None
stderr = None
# Only create this mapping if we haven't already.
if not self._communication_started:
self._fileobj2output = {}
if self.stdout:
self._fileobj2output[self.stdout] = []
if self.stderr:
self._fileobj2output[self.stderr] = []
if self.stdout:
stdout = self._fileobj2output[self.stdout]
if self.stderr:
stderr = self._fileobj2output[self.stderr]
self._save_input(input)
if self._input:
input_view = memoryview(self._input)
with _PopenSelector() as selector:
if self.stdin and input:
selector.register(self.stdin, selectors.EVENT_WRITE)
if self.stdout and not self.stdout.closed:
selector.register(self.stdout, selectors.EVENT_READ)
if self.stderr and not self.stderr.closed:
selector.register(self.stderr, selectors.EVENT_READ)
while selector.get_map():
timeout = self._remaining_time(endtime)
if timeout is not None and timeout < 0:
self._check_timeout(endtime, orig_timeout,
stdout, stderr,
skip_check_and_raise=True)
raise RuntimeError( # Impossible :)
'_check_timeout(..., skip_check_and_raise=True) '
'failed to raise TimeoutExpired.')
ready = selector.select(timeout)
self._check_timeout(endtime, orig_timeout, stdout, stderr)
# XXX Rewrite these to use non-blocking I/O on the file
# objects; they are no longer using C stdio!
for key, events in ready:
if key.fileobj is self.stdin:
chunk = input_view[self._input_offset :
self._input_offset + _PIPE_BUF]
try:
self._input_offset += os.write(key.fd, chunk)
except BrokenPipeError:
selector.unregister(key.fileobj)
key.fileobj.close()
else:
if self._input_offset >= len(self._input):
selector.unregister(key.fileobj)
key.fileobj.close()
elif key.fileobj in (self.stdout, self.stderr):
data = os.read(key.fd, 32768)
if not data:
selector.unregister(key.fileobj)
key.fileobj.close()
self._fileobj2output[key.fileobj].append(data)
self.wait(timeout=self._remaining_time(endtime))
# All data exchanged. Translate lists into strings.
if stdout is not None:
stdout = b''.join(stdout)
if stderr is not None:
stderr = b''.join(stderr)
# Translate newlines, if requested.
# This also turns bytes into strings.
if self.text_mode:
if stdout is not None:
stdout = self._translate_newlines(stdout,
self.stdout.encoding,
self.stdout.errors)
if stderr is not None:
stderr = self._translate_newlines(stderr,
self.stderr.encoding,
self.stderr.errors)
return (stdout, stderr)
def _save_input(self, input):
# This method is called from the _communicate_with_*() methods
# so that if we time out while communicating, we can continue
# sending input if we retry.
if self.stdin and self._input is None:
self._input_offset = 0
self._input = input
if input is not None and self.text_mode:
self._input = self._input.encode(self.stdin.encoding,
self.stdin.errors)
def send_signal(self, sig):
"""Send a signal to the process."""
# bpo-38630: Polling reduces the risk of sending a signal to the
# wrong process if the process completed, the Popen.returncode
# attribute is still None, and the pid has been reassigned
# (recycled) to a new different process. This race condition can
# happens in two cases.
#
# Case 1. Thread A calls Popen.poll(), thread B calls
# Popen.send_signal(). In thread A, waitpid() succeed and returns
# the exit status. Thread B calls kill() because poll() in thread A
# did not set returncode yet. Calling poll() in thread B prevents
# the race condition thanks to Popen._waitpid_lock.
#
# Case 2. waitpid(pid, 0) has been called directly, without
# using Popen methods: returncode is still None is this case.
# Calling Popen.poll() will set returncode to a default value,
# since waitpid() fails with ProcessLookupError.
self.poll()
if self.returncode is not None:
# Skip signalling a process that we know has already died.
return
# The race condition can still happen if the race condition
# described above happens between the returncode test
# and the kill() call.
try:
os.kill(self.pid, sig)
except ProcessLookupError:
# Supress the race condition error; bpo-40550.
pass
def terminate(self):
"""Terminate the process with SIGTERM
"""
self.send_signal(signal.SIGTERM)
def kill(self):
"""Kill the process with SIGKILL
"""
self.send_signal(signal.SIGKILL)
| (args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, user=None, group=None, extra_groups=None, encoding=None, errors=None, text=None, umask=-1, pipesize=-1) |
11,419 | subprocess | __del__ | null | def __del__(self, _maxsize=sys.maxsize, _warn=warnings.warn):
if not self._child_created:
# We didn't get to successfully create a child process.
return
if self.returncode is None:
# Not reading subprocess exit status creates a zombie process which
# is only destroyed at the parent python process exit
_warn("subprocess %s is still running" % self.pid,
ResourceWarning, source=self)
# In case the child hasn't been waited on, check if it's done.
self._internal_poll(_deadstate=_maxsize)
if self.returncode is None and _active is not None:
# Child is still running, keep us alive until we can wait on it.
_active.append(self)
| (self, _maxsize=9223372036854775807, _warn=<built-in function warn>) |
11,421 | subprocess | __exit__ | null | def __exit__(self, exc_type, value, traceback):
if self.stdout:
self.stdout.close()
if self.stderr:
self.stderr.close()
try: # Flushing a BufferedWriter may raise an error
if self.stdin:
self.stdin.close()
finally:
if exc_type == KeyboardInterrupt:
# https://bugs.python.org/issue25942
# In the case of a KeyboardInterrupt we assume the SIGINT
# was also already sent to our child processes. We can't
# block indefinitely as that is not user friendly.
# If we have not already waited a brief amount of time in
# an interrupted .wait() or .communicate() call, do so here
# for consistency.
if self._sigint_wait_secs > 0:
try:
self._wait(timeout=self._sigint_wait_secs)
except TimeoutExpired:
pass
self._sigint_wait_secs = 0 # Note that this has been done.
return # resume the KeyboardInterrupt
# Wait for the process to terminate, to avoid zombies.
self.wait()
| (self, exc_type, value, traceback) |
11,422 | subprocess | __init__ | Create new Popen instance. | def __init__(self, args, bufsize=-1, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=True,
shell=False, cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=True, start_new_session=False,
pass_fds=(), *, user=None, group=None, extra_groups=None,
encoding=None, errors=None, text=None, umask=-1, pipesize=-1):
"""Create new Popen instance."""
_cleanup()
# Held while anything is calling waitpid before returncode has been
# updated to prevent clobbering returncode if wait() or poll() are
# called from multiple threads at once. After acquiring the lock,
# code must re-check self.returncode to see if another thread just
# finished a waitpid() call.
self._waitpid_lock = threading.Lock()
self._input = None
self._communication_started = False
if bufsize is None:
bufsize = -1 # Restore default
if not isinstance(bufsize, int):
raise TypeError("bufsize must be an integer")
if pipesize is None:
pipesize = -1 # Restore default
if not isinstance(pipesize, int):
raise TypeError("pipesize must be an integer")
if _mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
else:
# POSIX
if pass_fds and not close_fds:
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
self.args = args
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.encoding = encoding
self.errors = errors
self.pipesize = pipesize
# Validate the combinations of text and universal_newlines
if (text is not None and universal_newlines is not None
and bool(universal_newlines) != bool(text)):
raise SubprocessError('Cannot disambiguate when both text '
'and universal_newlines are supplied but '
'different. Pass one or the other.')
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are -1 when not using PIPEs. The child objects are -1
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if _mswindows:
if p2cwrite != -1:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread != -1:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread != -1:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
self.text_mode = encoding or errors or text or universal_newlines
# PEP 597: We suppress the EncodingWarning in subprocess module
# for now (at Python 3.10), because we focus on files for now.
# This will be changed to encoding = io.text_encoding(encoding)
# in the future.
if self.text_mode and encoding is None:
self.encoding = encoding = "locale"
# How long to resume waiting on a child after the first ^C.
# There is no right value for this. The purpose is to be polite
# yet remain good for interactive users trying to exit a tool.
self._sigint_wait_secs = 0.25 # 1/xkcd221.getRandomNumber()
self._closed_child_pipe_fds = False
if self.text_mode:
if bufsize == 1:
line_buffering = True
# Use the default buffer size for the underlying binary streams
# since they don't support line buffering.
bufsize = -1
else:
line_buffering = False
gid = None
if group is not None:
if not hasattr(os, 'setregid'):
raise ValueError("The 'group' parameter is not supported on the "
"current platform")
elif isinstance(group, str):
try:
import grp
except ImportError:
raise ValueError("The group parameter cannot be a string "
"on systems without the grp module")
gid = grp.getgrnam(group).gr_gid
elif isinstance(group, int):
gid = group
else:
raise TypeError("Group must be a string or an integer, not {}"
.format(type(group)))
if gid < 0:
raise ValueError(f"Group ID cannot be negative, got {gid}")
gids = None
if extra_groups is not None:
if not hasattr(os, 'setgroups'):
raise ValueError("The 'extra_groups' parameter is not "
"supported on the current platform")
elif isinstance(extra_groups, str):
raise ValueError("Groups must be a list, not a string")
gids = []
for extra_group in extra_groups:
if isinstance(extra_group, str):
try:
import grp
except ImportError:
raise ValueError("Items in extra_groups cannot be "
"strings on systems without the "
"grp module")
gids.append(grp.getgrnam(extra_group).gr_gid)
elif isinstance(extra_group, int):
gids.append(extra_group)
else:
raise TypeError("Items in extra_groups must be a string "
"or integer, not {}"
.format(type(extra_group)))
# make sure that the gids are all positive here so we can do less
# checking in the C code
for gid_check in gids:
if gid_check < 0:
raise ValueError(f"Group ID cannot be negative, got {gid_check}")
uid = None
if user is not None:
if not hasattr(os, 'setreuid'):
raise ValueError("The 'user' parameter is not supported on "
"the current platform")
elif isinstance(user, str):
try:
import pwd
except ImportError:
raise ValueError("The user parameter cannot be a string "
"on systems without the pwd module")
uid = pwd.getpwnam(user).pw_uid
elif isinstance(user, int):
uid = user
else:
raise TypeError("User must be a string or an integer")
if uid < 0:
raise ValueError(f"User ID cannot be negative, got {uid}")
try:
if p2cwrite != -1:
self.stdin = io.open(p2cwrite, 'wb', bufsize)
if self.text_mode:
self.stdin = io.TextIOWrapper(self.stdin, write_through=True,
line_buffering=line_buffering,
encoding=encoding, errors=errors)
if c2pread != -1:
self.stdout = io.open(c2pread, 'rb', bufsize)
if self.text_mode:
self.stdout = io.TextIOWrapper(self.stdout,
encoding=encoding, errors=errors)
if errread != -1:
self.stderr = io.open(errread, 'rb', bufsize)
if self.text_mode:
self.stderr = io.TextIOWrapper(self.stderr,
encoding=encoding, errors=errors)
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals,
gid, gids, uid, umask,
start_new_session)
except:
# Cleanup if the child failed starting.
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except OSError:
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
if _mswindows and isinstance(fd, Handle):
fd.Close()
else:
os.close(fd)
except OSError:
pass
raise
| (self, args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, user=None, group=None, extra_groups=None, encoding=None, errors=None, text=None, umask=-1, pipesize=-1) |
11,423 | subprocess | __repr__ | null | def __repr__(self):
obj_repr = (
f"<{self.__class__.__name__}: "
f"returncode: {self.returncode} args: {self.args!r}>"
)
if len(obj_repr) > 80:
obj_repr = obj_repr[:76] + "...>"
return obj_repr
| (self) |
11,424 | subprocess | _check_timeout | Convenience for checking if a timeout has expired. | def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq,
skip_check_and_raise=False):
"""Convenience for checking if a timeout has expired."""
if endtime is None:
return
if skip_check_and_raise or _time() > endtime:
raise TimeoutExpired(
self.args, orig_timeout,
output=b''.join(stdout_seq) if stdout_seq else None,
stderr=b''.join(stderr_seq) if stderr_seq else None)
| (self, endtime, orig_timeout, stdout_seq, stderr_seq, skip_check_and_raise=False) |
11,425 | subprocess | _close_pipe_fds | null | def _close_pipe_fds(self,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
# self._devnull is not always defined.
devnull_fd = getattr(self, '_devnull', None)
with contextlib.ExitStack() as stack:
if _mswindows:
if p2cread != -1:
stack.callback(p2cread.Close)
if c2pwrite != -1:
stack.callback(c2pwrite.Close)
if errwrite != -1:
stack.callback(errwrite.Close)
else:
if p2cread != -1 and p2cwrite != -1 and p2cread != devnull_fd:
stack.callback(os.close, p2cread)
if c2pwrite != -1 and c2pread != -1 and c2pwrite != devnull_fd:
stack.callback(os.close, c2pwrite)
if errwrite != -1 and errread != -1 and errwrite != devnull_fd:
stack.callback(os.close, errwrite)
if devnull_fd is not None:
stack.callback(os.close, devnull_fd)
# Prevent a double close of these handles/fds from __init__ on error.
self._closed_child_pipe_fds = True
| (self, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) |
11,426 | subprocess | _communicate | null | def _communicate(self, input, endtime, orig_timeout):
if self.stdin and not self._communication_started:
# Flush stdio buffer. This might block, if the user has
# been writing to .stdin in an uncontrolled fashion.
try:
self.stdin.flush()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
if not input:
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore BrokenPipeError.
stdout = None
stderr = None
# Only create this mapping if we haven't already.
if not self._communication_started:
self._fileobj2output = {}
if self.stdout:
self._fileobj2output[self.stdout] = []
if self.stderr:
self._fileobj2output[self.stderr] = []
if self.stdout:
stdout = self._fileobj2output[self.stdout]
if self.stderr:
stderr = self._fileobj2output[self.stderr]
self._save_input(input)
if self._input:
input_view = memoryview(self._input)
with _PopenSelector() as selector:
if self.stdin and input:
selector.register(self.stdin, selectors.EVENT_WRITE)
if self.stdout and not self.stdout.closed:
selector.register(self.stdout, selectors.EVENT_READ)
if self.stderr and not self.stderr.closed:
selector.register(self.stderr, selectors.EVENT_READ)
while selector.get_map():
timeout = self._remaining_time(endtime)
if timeout is not None and timeout < 0:
self._check_timeout(endtime, orig_timeout,
stdout, stderr,
skip_check_and_raise=True)
raise RuntimeError( # Impossible :)
'_check_timeout(..., skip_check_and_raise=True) '
'failed to raise TimeoutExpired.')
ready = selector.select(timeout)
self._check_timeout(endtime, orig_timeout, stdout, stderr)
# XXX Rewrite these to use non-blocking I/O on the file
# objects; they are no longer using C stdio!
for key, events in ready:
if key.fileobj is self.stdin:
chunk = input_view[self._input_offset :
self._input_offset + _PIPE_BUF]
try:
self._input_offset += os.write(key.fd, chunk)
except BrokenPipeError:
selector.unregister(key.fileobj)
key.fileobj.close()
else:
if self._input_offset >= len(self._input):
selector.unregister(key.fileobj)
key.fileobj.close()
elif key.fileobj in (self.stdout, self.stderr):
data = os.read(key.fd, 32768)
if not data:
selector.unregister(key.fileobj)
key.fileobj.close()
self._fileobj2output[key.fileobj].append(data)
self.wait(timeout=self._remaining_time(endtime))
# All data exchanged. Translate lists into strings.
if stdout is not None:
stdout = b''.join(stdout)
if stderr is not None:
stderr = b''.join(stderr)
# Translate newlines, if requested.
# This also turns bytes into strings.
if self.text_mode:
if stdout is not None:
stdout = self._translate_newlines(stdout,
self.stdout.encoding,
self.stdout.errors)
if stderr is not None:
stderr = self._translate_newlines(stderr,
self.stderr.encoding,
self.stderr.errors)
return (stdout, stderr)
| (self, input, endtime, orig_timeout) |
11,427 | subprocess | _execute_child | Execute program (POSIX version) | 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,
gid, gids, uid, umask,
start_new_session):
"""Execute program (POSIX version)"""
if isinstance(args, (str, bytes)):
args = [args]
elif isinstance(args, os.PathLike):
if shell:
raise TypeError('path-like args is not allowed when '
'shell is true')
args = [args]
else:
args = list(args)
if shell:
# On Android the default shell is at '/system/bin/sh'.
unix_shell = ('/system/bin/sh' if
hasattr(sys, 'getandroidapilevel') else '/bin/sh')
args = [unix_shell, "-c"] + args
if executable:
args[0] = executable
if executable is None:
executable = args[0]
sys.audit("subprocess.Popen", executable, args, cwd, env)
if (_USE_POSIX_SPAWN
and os.path.dirname(executable)
and preexec_fn is None
and not close_fds
and not pass_fds
and cwd is None
and (p2cread == -1 or p2cread > 2)
and (c2pwrite == -1 or c2pwrite > 2)
and (errwrite == -1 or errwrite > 2)
and not start_new_session
and gid is None
and gids is None
and uid is None
and umask < 0):
self._posix_spawn(args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
return
orig_executable = executable
# For transferring possible exec failure from child to parent.
# Data format: "exception name:hex errno:description"
# Pickle is not used; it is complex and involves memory allocation.
errpipe_read, errpipe_write = os.pipe()
# errpipe_write must not be in the standard io 0, 1, or 2 fd range.
low_fds_to_close = []
while errpipe_write < 3:
low_fds_to_close.append(errpipe_write)
errpipe_write = os.dup(errpipe_write)
for low_fd in low_fds_to_close:
os.close(low_fd)
try:
try:
# We must avoid complex work that could involve
# malloc or free in the child process to avoid
# potential deadlocks, thus we do all this here.
# and pass it to fork_exec()
if env is not None:
env_list = []
for k, v in env.items():
k = os.fsencode(k)
if b'=' in k:
raise ValueError("illegal environment variable name")
env_list.append(k + b'=' + os.fsencode(v))
else:
env_list = None # Use execv instead of execve.
executable = os.fsencode(executable)
if os.path.dirname(executable):
executable_list = (executable,)
else:
# This matches the behavior of os._execvpe().
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, tuple(sorted(map(int, fds_to_keep))),
cwd, env_list,
p2cread, p2cwrite, c2pread, c2pwrite,
errread, errwrite,
errpipe_read, errpipe_write,
restore_signals, start_new_session,
gid, gids, uid, umask,
preexec_fn)
self._child_created = True
finally:
# be sure the FD is closed no matter what
os.close(errpipe_write)
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
# Wait for exec to fail or succeed; possibly raising an
# exception (limited in size)
errpipe_data = bytearray()
while True:
part = os.read(errpipe_read, 50000)
errpipe_data += part
if not part or len(errpipe_data) > 50000:
break
finally:
# be sure the FD is closed no matter what
os.close(errpipe_read)
if errpipe_data:
try:
pid, sts = os.waitpid(self.pid, 0)
if pid == self.pid:
self._handle_exitstatus(sts)
else:
self.returncode = sys.maxsize
except ChildProcessError:
pass
try:
exception_name, hex_errno, err_msg = (
errpipe_data.split(b':', 2))
# The encoding here should match the encoding
# written in by the subprocess implementations
# like _posixsubprocess
err_msg = err_msg.decode()
except ValueError:
exception_name = b'SubprocessError'
hex_errno = b'0'
err_msg = 'Bad exception data from child: {!r}'.format(
bytes(errpipe_data))
child_exception_type = getattr(
builtins, exception_name.decode('ascii'),
SubprocessError)
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 = ""
# The error must be from chdir(cwd).
err_filename = cwd
else:
err_filename = orig_executable
if errno_num != 0:
err_msg = os.strerror(errno_num)
raise child_exception_type(errno_num, err_msg, err_filename)
raise child_exception_type(err_msg)
| (self, args, executable, preexec_fn, close_fds, pass_fds, cwd, env, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite, restore_signals, gid, gids, uid, umask, start_new_session) |
11,428 | subprocess | _get_devnull | null | def _get_devnull(self):
if not hasattr(self, '_devnull'):
self._devnull = os.open(os.devnull, os.O_RDWR)
return self._devnull
| (self) |
11,429 | subprocess | _get_handles | Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
| def _get_handles(self, stdin, stdout, stderr):
"""Construct and return tuple with IO objects:
p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
"""
p2cread, p2cwrite = -1, -1
c2pread, c2pwrite = -1, -1
errread, errwrite = -1, -1
if stdin is None:
pass
elif stdin == PIPE:
p2cread, p2cwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(p2cwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdin == DEVNULL:
p2cread = self._get_devnull()
elif isinstance(stdin, int):
p2cread = stdin
else:
# Assuming file-like object
p2cread = stdin.fileno()
if stdout is None:
pass
elif stdout == PIPE:
c2pread, c2pwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(c2pwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stdout == DEVNULL:
c2pwrite = self._get_devnull()
elif isinstance(stdout, int):
c2pwrite = stdout
else:
# Assuming file-like object
c2pwrite = stdout.fileno()
if stderr is None:
pass
elif stderr == PIPE:
errread, errwrite = os.pipe()
if self.pipesize > 0 and hasattr(fcntl, "F_SETPIPE_SZ"):
fcntl.fcntl(errwrite, fcntl.F_SETPIPE_SZ, self.pipesize)
elif stderr == STDOUT:
if c2pwrite != -1:
errwrite = c2pwrite
else: # child's stdout is not set, use parent's stdout
errwrite = sys.__stdout__.fileno()
elif stderr == DEVNULL:
errwrite = self._get_devnull()
elif isinstance(stderr, int):
errwrite = stderr
else:
# Assuming file-like object
errwrite = stderr.fileno()
return (p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
| (self, stdin, stdout, stderr) |
11,430 | subprocess | _handle_exitstatus | All callers to this function MUST hold self._waitpid_lock. | def _handle_exitstatus(self, sts,
waitstatus_to_exitcode=os.waitstatus_to_exitcode,
_WIFSTOPPED=os.WIFSTOPPED,
_WSTOPSIG=os.WSTOPSIG):
"""All callers to this function MUST hold self._waitpid_lock."""
# This method is called (indirectly) by __del__, so it cannot
# refer to anything outside of its local scope.
if _WIFSTOPPED(sts):
self.returncode = -_WSTOPSIG(sts)
else:
self.returncode = waitstatus_to_exitcode(sts)
| (self, sts, waitstatus_to_exitcode=<built-in function waitstatus_to_exitcode>, _WIFSTOPPED=<built-in function WIFSTOPPED>, _WSTOPSIG=<built-in function WSTOPSIG>) |
11,431 | subprocess | _internal_poll | Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it cannot reference anything
outside of the local scope (nor can any methods it calls).
| def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
_WNOHANG=os.WNOHANG, _ECHILD=errno.ECHILD):
"""Check if child process has terminated. Returns returncode
attribute.
This method is called by __del__, so it cannot reference anything
outside of the local scope (nor can any methods it calls).
"""
if self.returncode is None:
if not self._waitpid_lock.acquire(False):
# Something else is busy calling waitpid. Don't allow two
# at once. We know nothing yet.
return None
try:
if self.returncode is not None:
return self.returncode # Another thread waited.
pid, sts = _waitpid(self.pid, _WNOHANG)
if pid == self.pid:
self._handle_exitstatus(sts)
except OSError as e:
if _deadstate is not None:
self.returncode = _deadstate
elif e.errno == _ECHILD:
# This happens if SIGCLD is set to be ignored or
# waiting for child processes has otherwise been
# disabled for our process. This child is dead, we
# can't get the status.
# http://bugs.python.org/issue15756
self.returncode = 0
finally:
self._waitpid_lock.release()
return self.returncode
| (self, _deadstate=None, _waitpid=<built-in function waitpid>, _WNOHANG=1, _ECHILD=10) |
11,432 | subprocess | _posix_spawn | Execute program using os.posix_spawn(). | def _posix_spawn(self, args, executable, env, restore_signals,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite):
"""Execute program using os.posix_spawn()."""
if env is None:
env = os.environ
kwargs = {}
if restore_signals:
# See _Py_RestoreSignals() in Python/pylifecycle.c
sigset = []
for signame in ('SIGPIPE', 'SIGXFZ', 'SIGXFSZ'):
signum = getattr(signal, signame, None)
if signum is not None:
sigset.append(signum)
kwargs['setsigdef'] = sigset
file_actions = []
for fd in (p2cwrite, c2pread, errread):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_CLOSE, fd))
for fd, fd2 in (
(p2cread, 0),
(c2pwrite, 1),
(errwrite, 2),
):
if fd != -1:
file_actions.append((os.POSIX_SPAWN_DUP2, fd, fd2))
if file_actions:
kwargs['file_actions'] = file_actions
self.pid = os.posix_spawn(executable, args, env, **kwargs)
self._child_created = True
self._close_pipe_fds(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite)
| (self, args, executable, env, restore_signals, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite) |
11,433 | subprocess | _remaining_time | Convenience for _communicate when computing timeouts. | def _remaining_time(self, endtime):
"""Convenience for _communicate when computing timeouts."""
if endtime is None:
return None
else:
return endtime - _time()
| (self, endtime) |
11,434 | subprocess | _save_input | null | def _save_input(self, input):
# This method is called from the _communicate_with_*() methods
# so that if we time out while communicating, we can continue
# sending input if we retry.
if self.stdin and self._input is None:
self._input_offset = 0
self._input = input
if input is not None and self.text_mode:
self._input = self._input.encode(self.stdin.encoding,
self.stdin.errors)
| (self, input) |
11,435 | subprocess | _stdin_write | null | def _stdin_write(self, input):
if input:
try:
self.stdin.write(input)
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
# bpo-19612, bpo-30418: On Windows, stdin.write() fails
# with EINVAL if the child process exited or if the child
# process is still running but closed the pipe.
pass
else:
raise
try:
self.stdin.close()
except BrokenPipeError:
pass # communicate() must ignore broken pipe errors.
except OSError as exc:
if exc.errno == errno.EINVAL:
pass
else:
raise
| (self, input) |
11,436 | subprocess | _translate_newlines | null | def _translate_newlines(self, data, encoding, errors):
data = data.decode(encoding, errors)
return data.replace("\r\n", "\n").replace("\r", "\n")
| (self, data, encoding, errors) |
11,437 | subprocess | _try_wait | All callers to this function MUST hold self._waitpid_lock. | def _try_wait(self, wait_flags):
"""All callers to this function MUST hold self._waitpid_lock."""
try:
(pid, sts) = os.waitpid(self.pid, wait_flags)
except ChildProcessError:
# This happens if SIGCLD is set to be ignored or waiting
# for child processes has otherwise been disabled for our
# process. This child is dead, we can't get the status.
pid = self.pid
sts = 0
return (pid, sts)
| (self, wait_flags) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.