Ce reprezinta codul? [PYTHON]

Deconectat
Avatar utilizator
Oenomaus
Nivel 2
Nivel 2
Mesaje: 198
Membru din: 09 Sep 2015
Status: Sunt bine mersi ^.^
Server Metin2: Da
Regat: Chunjo
Mulțumiri acordate: 1
Mulțumiri primite: 7

Ce reprezinta codul? [PYTHON]

Mesajde Oenomaus » 21 Aug 2018, 15:10

Va intreb pentru ca sunt prezente in folderul unui server de metin2 si sunt nelamurit in legatura cu ele.

Primul cod:

"""Record of phased-in incompatible language changes.

Each line is of the form:

FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
CompilerFlag ")"

where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples
of the same form as sys.version_info:

(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
PY_MINOR_VERSION, # the 1; an int
PY_MICRO_VERSION, # the 0; an int
PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
PY_RELEASE_SERIAL # the 3; an int
)

OptionalRelease records the first release in which

from __future__ import FeatureName

was accepted.

In the case of MandatoryReleases that have not yet occurred,
MandatoryRelease predicts the release in which the feature will become part
of the language.

Else MandatoryRelease records when the feature became part of the language;
in releases at or after that, modules no longer need

from __future__ import FeatureName

to use the feature in question, but may continue to use such imports.

MandatoryRelease may also be None, meaning that a planned feature got
dropped.

Instances of class _Feature have two corresponding methods,
.getOptionalRelease() and .getMandatoryRelease().

CompilerFlag is the (bitfield) flag that should be passed in the fourth
argument to the builtin function compile() to enable the feature in
dynamically compiled code. This flag is stored in the .compiler_flag
attribute on _Future instances. These values must match the appropriate
#defines of CO_xxx flags in Include/compile.h.

No feature line is ever to be deleted from this file.
"""

all_feature_names = [
"nested_scopes",
"generators",
"division",
]

__all__ = ["all_feature_names"] + all_feature_names

# The CO_xxx symbols are defined here under the same names used by
# compile.h, so that an editor search will find them here. However,
# they're not exported in __all__, because they don't really belong to
# this module.
CO_NESTED = 0x0010 # nested_scopes
CO_GENERATOR_ALLOWED = 0x1000 # generators
CO_FUTURE_DIVISION = 0x2000 # division

class _Feature:
def __init__(self, optionalRelease, mandatoryRelease, compiler_flag):
self.optional = optionalRelease
self.mandatory = mandatoryRelease
self.compiler_flag = compiler_flag

def getOptionalRelease(self):
"""Return first release in which this feature was recognized.

This is a 5-tuple, of the same form as sys.version_info.
"""

return self.optional

def getMandatoryRelease(self):
"""Return release in which this feature will become mandatory.

This is a 5-tuple, of the same form as sys.version_info, or, if
the feature was dropped, is None.
"""

return self.mandatory

def __repr__(self):
return "_Feature" + repr((self.optional,
self.mandatory,
self.compiler_flag))

nested_scopes = _Feature((2, 1, 0, "beta", 1),
(2, 2, 0, "alpha", 0),
CO_NESTED)

generators = _Feature((2, 2, 0, "alpha", 1),
(2, 3, 0, "final", 0),
CO_GENERATOR_ALLOWED)

division = _Feature((2, 2, 0, "alpha", 2),
(3, 0, 0, "alpha", 0),
CO_FUTURE_DIVISION)


Codul 2 :
"""Helper to provide extensibility for pickle/cPickle.

This is only useful to add pickle support for extension types defined in
C, not for instances of user-defined classes.
"""

from types import ClassType as _ClassType

__all__ = ["pickle","constructor"]

dispatch_table = {}
safe_constructors = {}

def pickle(ob_type, pickle_function, constructor_ob=None):
if type(ob_type) is _ClassType:
raise TypeError("copy_reg is not intended for use with classes")

if not callable(pickle_function):
raise TypeError("reduction functions must be callable")
dispatch_table[ob_type] = pickle_function

if constructor_ob is not None:
constructor(constructor_ob)

def constructor(object):
if not callable(object):
raise TypeError("constructors must be callable")
safe_constructors[object] = 1

# Example: provide pickling support for complex numbers.

def pickle_complex(c):
return complex, (c.real, c.imag)

pickle(type(1j), pickle_complex, complex)

# Support for picking new-style objects

def _reconstructor(cls, base, state):
obj = base.__new__(cls, state)
base.__init__(obj, state)
return obj
_reconstructor.__safe_for_unpickling__ = 1

_HEAPTYPE = 1<<9

def _reduce(self):
for base in self.__class__.__mro__:
if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
break
else:
base = object # not really reachable
if base is object:
state = None
else:
if base is self.__class__:
raise TypeError, "can't pickle %s objects" % base.__name__
state = base(self)
args = (self.__class__, base, state)
try:
getstate = self.__getstate__
except AttributeError:
try:
dict = self.__dict__
except AttributeError:
dict = None
else:
dict = getstate()
if dict:
return _reconstructor, args, dict
else:
return _reconstructor, args


Codul3
# Module 'ntpath' -- common operations on WinNT/Win95 pathnames
"""Common pathname manipulations, WindowsNT/95 version.

Instead of importing this module directly, import os and refer to this
module as os.path.
"""

import os
import stat

__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","islink","exists","isdir","isfile","ismount",
"walk","expanduser","expandvars","normpath","abspath","splitunc",
"realpath"]

# Normalize the case of a pathname and map slashes to backslashes.
# Other normalizations (such as optimizing '../' away) are not done
# (this is done by normpath).

def normcase(s):
"""Normalize case of pathname.

Makes all characters lowercase and all slashes into backslashes."""
return s.replace("/", "\\").lower()


# Return whether a path is absolute.
# Trivial in Posix, harder on the Mac or MS-DOS.
# For DOS it is absolute if it starts with a slash or backslash (current
# volume), or if a pathname after the volume letter and colon / UNC resource
# starts with a slash or backslash.

def isabs(s):
"""Test whether a path is absolute"""
s = splitdrive(s)[1]
return s != '' and s[:1] in '/\\'


# Join two (or more) paths.

def join(a, *p):
"""Join two or more pathname components, inserting "\\" as needed"""
path = a
for b in p:
b_wins = 0 # set to 1 iff b makes path irrelevant
if path == "":
b_wins = 1

elif isabs(b):
# This probably wipes out path so far. However, it's more
# complicated if path begins with a drive letter:
# 1. join('c:', '/a') == 'c:/a'
# 2. join('c:/', '/a') == 'c:/a'
# But
# 3. join('c:/a', '/b') == '/b'
# 4. join('c:', 'd:/') = 'd:/'
# 5. join('c:/', 'd:/') = 'd:/'
if path[1:2] != ":" or b[1:2] == ":":
# Path doesn't start with a drive letter, or cases 4 and 5.
b_wins = 1

# Else path has a drive letter, and b doesn't but is absolute.
elif len(path) > 3 or (len(path) == 3 and
path[-1] not in "/\\"):
# case 3
b_wins = 1

if b_wins:
path = b
else:
# Join, and ensure there's a separator.
assert len(path) > 0
if path[-1] in "/\\":
if b and b[0] in "/\\":
path += b[1:]
else:
path += b
elif path[-1] == ":":
path += b
elif b:
if b[0] in "/\\":
path += b
else:
path += "\\" + b
else:
# path is not empty and does not end with a backslash,
# but b is empty; since, e.g., split('a/') produces
# ('a', ''), it's best if join() adds a backslash in
# this case.
path += '\\'

return path


# Split a path in a drive specification (a drive letter followed by a
# colon) and the path specification.
# It is always true that drivespec + pathspec == p
def splitdrive(p):
"""Split a pathname into drive and path specifiers. Returns a 2-tuple
"(drive,path)"; either part may be empty"""
if p[1:2] == ':':
return p[0:2], p[2:]
return '', p


# Parse UNC paths
def splitunc(p):
"""Split a pathname into UNC mount point and relative path specifiers.

Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
"""
if p[1:2] == ':':
return '', p # Drive letter present
firstTwo = p[0:2]
if firstTwo == '//' or firstTwo == '\\\\':
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
# \\machine\mountpoint\directories...
# directory ^^^^^^^^^^^^^^^
normp = normcase(p)
index = normp.find('\\', 2)
if index == -1:
##raise RuntimeError, 'illegal UNC path: "' + p + '"'
return ("", p)
index = normp.find('\\', index + 1)
if index == -1:
index = len(p)
return p[:index], p[index:]
return '', p


# Split a path in head (everything up to the last '/') and tail (the
# rest). After the trailing '/' is stripped, the invariant
# join(head, tail) == p holds.
# The resulting head won't end in '/' unless it is the root.

def split(p):
"""Split a pathname.

Return tuple (head, tail) where tail is everything after the final slash.
Either part may be empty."""

d, p = splitdrive(p)
# set i to index beyond p's last slash
i = len(p)
while i and p[i-1] not in '/\\':
i = i - 1
head, tail = p[:i], p[i:] # now tail has no slashes
# remove trailing slashes from head, unless it's all slashes
head2 = head
while head2 and head2[-1] in '/\\':
head2 = head2[:-1]
head = head2 or head
return d + head, tail


# Split a path in root and extension.
# The extension is everything starting at the last dot in the last
# pathname component; the root is everything before that.
# It is always true that root + ext == p.

def splitext(p):
"""Split the extension from a pathname.

Extension is everything from the last dot to the end.
Return (root, ext), either part may be empty."""
root, ext = '', ''
for c in p:
if c in ['/','\\']:
root, ext = root + ext + c, ''
elif c == '.':
if ext:
root, ext = root + ext, c
else:
ext = c
elif ext:
ext = ext + c
else:
root = root + c
return root, ext


# Return the tail (basename) part of a path.

def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]


# Return the head (dirname) part of a path.

def dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0]


# Return the longest prefix of all list elements.

def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
prefix = m[0]
for item in m:
for i in range(len(prefix)):
if prefix[:i+1] != item[:i+1]:
prefix = prefix[:i]
if i == 0: return ''
break
return prefix


# Get size, mtime, atime of files.

def getsize(filename):
"""Return the size of a file, reported by os.stat()"""
st = os.stat(filename)
return st[stat.ST_SIZE]

def getmtime(filename):
"""Return the last modification time of a file, reported by os.stat()"""
st = os.stat(filename)
return st[stat.ST_MTIME]

def getatime(filename):
"""Return the last access time of a file, reported by os.stat()"""
st = os.stat(filename)
return st[stat.ST_ATIME]


# Is a path a symbolic link?
# This will always return false on systems where posix.lstat doesn't exist.

def islink(path):
"""Test for symbolic link. On WindowsNT/95 always returns false"""
return 0


# Does a path exist?
# This is false for dangling symbolic links.

def exists(path):
"""Test whether a path exists"""
try:
st = os.stat(path)
except os.error:
return 0
return 1


# Is a path a dos directory?
# This follows symbolic links, so both islink() and isdir() can be true
# for the same path.

def isdir(path):
"""Test whether a path is a directory"""
try:
st = os.stat(path)
except os.error:
return 0
return stat.S_ISDIR(st[stat.ST_MODE])


# Is a path a regular file?
# This follows symbolic links, so both islink() and isdir() can be true
# for the same path.

def isfile(path):
"""Test whether a path is a regular file"""
try:
st = os.stat(path)
except os.error:
return 0
return stat.S_ISREG(st[stat.ST_MODE])


# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.

def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\'


# Directory tree walk.
# For each directory under top (including top itself, but excluding
# '.' and '..'), func(arg, dirname, filenames) is called, where
# dirname is the name of the directory and filenames is the list
# files files (and subdirectories etc.) in the directory.
# The func may modify the filenames list, to implement a filter,
# or to impose a different order of visiting.

def walk(top, func, arg):
"""Directory tree walk with callback function.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
dirname is the name of the directory, and fnames a list of the names of
the files and subdirectories in dirname (excluding '.' and '..'). func
may modify the fnames list in-place (e.g. via del or slice assignment),
and walk will only recurse into the subdirectories whose names remain in
fnames; this can be used to implement a filter, or to impose a specific
order of visiting. No semantics are defined for, or required of, arg,
beyond that arg is always passed to func. It can be used, e.g., to pass
a filename pattern, or a mutable object designed to accumulate
statistics. Passing None for arg is common."""

try:
names = os.listdir(top)
except os.error:
return
func(arg, top, names)
exceptions = ('.', '..')
for name in names:
if name not in exceptions:
name = join(top, name)
if isdir(name):
walk(name, func, arg)


# Expand paths beginning with '~' or '~user'.
# '~' means $HOME; '~user' means that user's home directory.
# If the path doesn't begin with '~', or if the user or $HOME is unknown,
# the path is returned unchanged (leaving error reporting to whatever
# function is called with the expanded path as argument).
# See also module 'glob' for expansion of *, ? and [...] in pathnames.
# (A function should also be defined to do full *sh-style environment
# variable expansion.)

def expanduser(path):
"""Expand ~ and ~user constructs.

If user or $HOME is unknown, do nothing."""
if path[:1] != '~':
return path
i, n = 1, len(path)
while i < n and path[i] not in '/\\':
i = i + 1
if i == 1:
if os.environ.has_key('HOME'):
userhome = os.environ['HOME']
elif not os.environ.has_key('HOMEPATH'):
return path
else:
try:
drive = os.environ['HOMEDRIVE']
except KeyError:
drive = ''
userhome = join(drive, os.environ['HOMEPATH'])
else:
return path
return userhome + path[i:]


# Expand paths containing shell variable substitutions.
# The following rules apply:
# - no expansion within single quotes
# - no escape character, except for '$$' which is translated into '$'
# - ${varname} is accepted.
# - varnames can be made out of letters, digits and the character '_'
# XXX With COMMAND.COM you can use any characters in a variable name,
# XXX except '^|<>='.

def expandvars(path):
"""Expand shell variables of form $var and ${var}.

Unknown variables are left unchanged."""
if '$' not in path:
return path
import string
varchars = string.ascii_letters + string.digits + '_-'
res = ''
index = 0
pathlen = len(path)
while index < pathlen:
c = path[index]
if c == '\'': # no expansion within single quotes
path = path[index + 1:]
pathlen = len(path)
try:
index = path.index('\'')
res = res + '\'' + path[:index + 1]
except ValueError:
res = res + path
index = pathlen - 1
elif c == '$': # variable or '$$'
if path[index + 1:index + 2] == '$':
res = res + c
index = index + 1
elif path[index + 1:index + 2] == '{':
path = path[index+2:]
pathlen = len(path)
try:
index = path.index('}')
var = path[:index]
if os.environ.has_key(var):
res = res + os.environ[var]
except ValueError:
res = res + path
index = pathlen - 1
else:
var = ''
index = index + 1
c = path[index:index + 1]
while c != '' and c in varchars:
var = var + c
index = index + 1
c = path[index:index + 1]
if os.environ.has_key(var):
res = res + os.environ[var]
if c != '':
res = res + c
else:
res = res + c
index = index + 1
return res


# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A\B.
# Previously, this function also truncated pathnames to 8+3 format,
# but as this module is called "ntpath", that's obviously wrong!

def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
path = path.replace("/", "\\")
prefix, path = splitdrive(path)
while path[:1] == "\\":
prefix = prefix + "\\"
path = path[1:]
comps = path.split("\\")
i = 0
while i < len(comps):
if comps[i] in ('.', ''):
del comps[i]
elif comps[i] == '..':
if i > 0 and comps[i-1] != '..':
del comps[i-1:i+1]
i -= 1
elif i == 0 and prefix.endswith("\\"):
del comps[i]
else:
i += 1
else:
i += 1
# If the path is now empty, substitute '.'
if not prefix and not comps:
comps.append('.')
return prefix + "\\".join(comps)


# Return an absolute path.
def abspath(path):
"""Return the absolute version of a path"""
try:
from nt import _getfullpathname
except ImportError: # Not running on Windows - mock up something sensible.
global abspath
def _abspath(path):
if not isabs(path):
path = join(os.getcwd(), path)
return normpath(path)
abspath = _abspath
return _abspath(path)

if path: # Empty path must return current working directory.
try:
path = _getfullpathname(path)
except WindowsError:
pass # Bad path - return unchanged.
else:
path = os.getcwd()
return normpath(path)

# realpath is a no-op on systems without islink support
realpath = abspath


Codul4
r"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.

This exports:
- all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, macpath, or dospath
- os.name is 'posix', 'nt', 'dos', 'os2', 'mac', 'ce' or 'riscos'
- os.curdir is a string representing the current directory ('.' or ':')
- os.pardir is a string representing the parent directory ('..' or '::')
- os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
- os.extsep is the extension separator ('.' or '/')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables

Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
"""

#'

import sys

_names = sys.builtin_module_names

altsep = None

__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
"defpath", "name"]

def _get_exports_list(module):
try:
return list(module.__all__)
except AttributeError:
return [n for n in dir(module) if n[0] != '_']

if 'posix' in _names:
name = 'posix'
linesep = '\n'
curdir = '.'; pardir = '..'; sep = '/'; pathsep = ':'
defpath = ':/bin:/usr/bin'
from posix import *
try:
from posix import _exit
except ImportError:
pass
import posixpath
path = posixpath
del posixpath

import posix
__all__.extend(_get_exports_list(posix))
del posix

elif 'nt' in _names:
name = 'nt'
linesep = '\r\n'
curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
defpath = '.;C:\\bin'
altsep = '/'
from nt import *
for i in ['_exit']:
try:
exec "from nt import " + i
except ImportError:
pass
import ntpath
path = ntpath
del ntpath

import nt
__all__.extend(_get_exports_list(nt))
del nt

elif 'dos' in _names:
name = 'dos'
linesep = '\r\n'
curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
defpath = '.;C:\\bin'
from dos import *
try:
from dos import _exit
except ImportError:
pass
import dospath
path = dospath
del dospath

import dos
__all__.extend(_get_exports_list(dos))
del dos

elif 'os2' in _names:
name = 'os2'
linesep = '\r\n'
curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
defpath = '.;C:\\bin'
from os2 import *
try:
from os2 import _exit
except ImportError:
pass
import ntpath
path = ntpath
del ntpath

import os2
__all__.extend(_get_exports_list(os2))
del os2

elif 'mac' in _names:
name = 'mac'
linesep = '\r'
curdir = ':'; pardir = '::'; sep = ':'; pathsep = '\n'
defpath = ':'
from mac import *
try:
from mac import _exit
except ImportError:
pass
import macpath
path = macpath
del macpath

import mac
__all__.extend(_get_exports_list(mac))
del mac

elif 'ce' in _names:
name = 'ce'
linesep = '\r\n'
curdir = '.'; pardir = '..'; sep = '\\'; pathsep = ';'
defpath = '\\Windows'
from ce import *
for i in ['_exit']:
try:
exec "from ce import " + i
except ImportError:
pass
# We can use the standard Windows path.
import ntpath
path = ntpath
del ntpath

import ce
__all__.extend(_get_exports_list(ce))
del ce

elif 'riscos' in _names:
name = 'riscos'
linesep = '\n'
curdir = '@'; pardir = '^'; sep = '.'; pathsep = ','
defpath = '<Run$Dir>'
from riscos import *
try:
from riscos import _exit
except ImportError:
pass
import riscospath
path = riscospath
del riscospath

import riscos
__all__.extend(_get_exports_list(riscos))
del riscos

else:
raise ImportError, 'no os specific module found'


if sep=='.':
extsep = '/'
else:
extsep = '.'

__all__.append("path")

del _names

sys.modules['os.path'] = path

#'

# Super directory utilities.
# (Inspired by Eric Raymond; the doc strings are mostly his)

def makedirs(name, mode=0777):
"""makedirs(path [, mode=0777]) -> None

Super-mkdir; create a leaf directory and all intermediate ones.
Works like mkdir, except that any intermediate path segment (not
just the rightmost) will be created if it does not exist. This is
recursive.

"""
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
if head and tail and not path.exists(head):
makedirs(head, mode)
mkdir(name, mode)

def removedirs(name):
"""removedirs(path) -> None

Super-rmdir; remove a leaf directory and empty all intermediate
ones. Works like rmdir except that, if the leaf directory is
successfully removed, directories corresponding to rightmost path
segments will be pruned way until either the whole path is
consumed or an error occurs. Errors during this latter phase are
ignored -- they generally mean that a directory was not empty.

"""
rmdir(name)
head, tail = path.split(name)
if not tail:
head, tail = path.split(head)
while head and tail:
try:
rmdir(head)
except error:
break
head, tail = path.split(head)

def renames(old, new):
"""renames(old, new) -> None

Super-rename; create directories as necessary and delete any left
empty. Works like rename, except creation of any intermediate
directories needed to make the new pathname good is attempted
first. After the rename, directories corresponding to rightmost
path segments of the old name will be pruned way until either the
whole path is consumed or a nonempty directory is found.

Note: this function can fail with the new directory structure made
if you lack permissions needed to unlink the leaf directory or
file.

"""
head, tail = path.split(new)
if head and tail and not path.exists(head):
makedirs(head)
rename(old, new)
head, tail = path.split(old)
if head and tail:
try:
removedirs(head)
except error:
pass

__all__.extend(["makedirs", "removedirs", "renames"])

# Make sure os.environ exists, at least
try:
environ
except NameError:
environ = {}

def execl(file, *args):
"""execl(file, *args)

Execute the executable file with argument list args, replacing the
current process. """
execv(file, args)

def execle(file, *args):
"""execle(file, *args, env)

Execute the executable file with argument list args and
environment env, replacing the current process. """
env = args[-1]
execve(file, args[:-1], env)

def execlp(file, *args):
"""execlp(file, *args)

Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process. """
execvp(file, args)

def execlpe(file, *args):
"""execlpe(file, *args, env)

Execute the executable file (which is searched for along $PATH)
with argument list args and environment env, replacing the current
process. """
env = args[-1]
execvpe(file, args[:-1], env)

def execvp(file, args):
"""execp(file, args)

Execute the executable file (which is searched for along $PATH)
with argument list args, replacing the current process.
args may be a list or tuple of strings. """
_execvpe(file, args)

def execvpe(file, args, env):
"""execvpe(file, args, env)

Execute the executable file (which is searched for along $PATH)
with argument list args and environment env , replacing the
current process.
args may be a list or tuple of strings. """
_execvpe(file, args, env)

__all__.extend(["execl","execle","execlp","execlpe","execvp","execvpe"])

def _execvpe(file, args, env=None):
from errno import ENOENT, ENOTDIR

if env is not None:
func = execve
argrest = (args, env)
else:
func = execv
argrest = (args,)
env = environ

head, tail = path.split(file)
if head:
apply(func, (file,) + argrest)
return
if env.has_key('PATH'):
envpath = env['PATH']
else:
envpath = defpath
PATH = envpath.split(pathsep)
saved_exc = None
saved_tb = None
for dir in PATH:
fullname = path.join(dir, file)
try:
apply(func, (fullname,) + argrest)
except error, e:
tb = sys.exc_info()[2]
if (e.errno != ENOENT and e.errno != ENOTDIR
and saved_exc is None):
saved_exc = e
saved_tb = tb
if saved_exc:
raise error, saved_exc, saved_tb
raise error, e, tb

# Change environ to automatically call putenv() if it exists
try:
# This will fail if there's no putenv
putenv
except NameError:
pass
else:
import UserDict

# Fake unsetenv() for Windows
# not sure about os2 and dos here but
# I'm guessing they are the same.

if name in ('os2', 'nt', 'dos'):
def unsetenv(key):
putenv(key, "")

if name == "riscos":
# On RISC OS, all env access goes through getenv and putenv
from riscosenviron import _Environ
elif name in ('os2', 'nt', 'dos'): # Where Env Var Names Must Be UPPERCASE
# But we store them as upper case
class _Environ(UserDict.IterableUserDict):
def __init__(self, environ):
UserDict.UserDict.__init__(self)
data = self.data
for k, v in environ.items():
data[k.upper()] = v
def __setitem__(self, key, item):
putenv(key, item)
self.data[key.upper()] = item
def __getitem__(self, key):
return self.data[key.upper()]
try:
unsetenv
except NameError:
def __delitem__(self, key):
del self.data[key.upper()]
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key.upper()]
def has_key(self, key):
return self.data.has_key(key.upper())
def get(self, key, failobj=None):
return self.data.get(key.upper(), failobj)
def update(self, dict):
for k, v in dict.items():
self[k] = v

else: # Where Env Var Names Can Be Mixed Case
class _Environ(UserDict.IterableUserDict):
def __init__(self, environ):
UserDict.UserDict.__init__(self)
self.data = environ
def __setitem__(self, key, item):
putenv(key, item)
self.data[key] = item
def update(self, dict):
for k, v in dict.items():
self[k] = v
try:
unsetenv
except NameError:
pass
else:
def __delitem__(self, key):
unsetenv(key)
del self.data[key]


environ = _Environ(environ)

def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default."""
return environ.get(key, default)
__all__.append("getenv")

def _exists(name):
try:
eval(name)
return 1
except NameError:
return 0

# Supply spawn*() (probably only for Unix)
if _exists("fork") and not _exists("spawnv") and _exists("execv"):

P_WAIT = 0
P_NOWAIT = P_NOWAITO = 1

# XXX Should we support P_DETACH? I suppose it could fork()**2
# and close the std I/O streams. Also, P_OVERLAY is the same
# as execv*()?

def _spawnvef(mode, file, args, env, func):
# Internal helper; func is the exec*() function to use
pid = fork()
if not pid:
# Child
try:
if env is None:
func(file, args)
else:
func(file, args, env)
except:
_exit(127)
else:
# Parent
if mode == P_NOWAIT:
return pid # Caller is responsible for waiting!
while 1:
wpid, sts = waitpid(pid, 0)
if WIFSTOPPED(sts):
continue
elif WIFSIGNALED(sts):
return -WTERMSIG(sts)
elif WIFEXITED(sts):
return WEXITSTATUS(sts)
else:
raise error, "Not stopped, signaled or exited???"

def spawnv(mode, file, args):
"""spawnv(mode, file, args) -> integer

Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, None, execv)

def spawnve(mode, file, args, env):
"""spawnve(mode, file, args, env) -> integer

Execute file with arguments from args in a subprocess with the
specified environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, env, execve)

# Note: spawnvp[e] is't currently supported on Windows

def spawnvp(mode, file, args):
"""spawnvp(mode, file, args) -> integer

Execute file (which is looked for along $PATH) with arguments from
args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, None, execvp)

def spawnvpe(mode, file, args, env):
"""spawnvpe(mode, file, args, env) -> integer

Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return _spawnvef(mode, file, args, env, execvpe)

if _exists("spawnv"):
# These aren't supplied by the basic Windows code
# but can be easily implemented in Python

def spawnl(mode, file, *args):
"""spawnl(mode, file, *args) -> integer

Execute file with arguments from args in a subprocess.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return spawnv(mode, file, args)

def spawnle(mode, file, *args):
"""spawnle(mode, file, *args, env) -> integer

Execute file with arguments from args in a subprocess with the
supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env = args[-1]
return spawnve(mode, file, args[:-1], env)

if _exists("spawnvp"):
# At the moment, Windows doesn't implement spawnvp[e],
# so it won't have spawnlp[e] either.
def spawnlp(mode, file, *args):
"""spawnlp(mode, file, *args, env) -> integer

Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
return spawnvp(mode, file, args)

def spawnlpe(mode, file, *args):
"""spawnlpe(mode, file, *args, env) -> integer

Execute file (which is looked for along $PATH) with arguments from
args in a subprocess with the supplied environment.
If mode == P_NOWAIT return the pid of the process.
If mode == P_WAIT return the process's exit code if it exits normally;
otherwise return -SIG, where SIG is the signal that killed it. """
env = args[-1]
return spawnvpe(mode, file, args[:-1], env)


__all__.extend(["spawnlp","spawnlpe","spawnv", "spawnve","spawnvp",
"spawnvpe","spawnl","spawnle",])


# Supply popen2 etc. (for Unix)
if _exists("fork"):
if not _exists("popen2"):
def popen2(cmd, mode="t", bufsize=-1):
import popen2
stdout, stdin = popen2.popen2(cmd, bufsize)
return stdin, stdout
__all__.append("popen2")

if not _exists("popen3"):
def popen3(cmd, mode="t", bufsize=-1):
import popen2
stdout, stdin, stderr = popen2.popen3(cmd, bufsize)
return stdin, stdout, stderr
__all__.append("popen3")

if not _exists("popen4"):
def popen4(cmd, mode="t", bufsize=-1):
import popen2
stdout, stdin = popen2.popen4(cmd, bufsize)
return stdin, stdout
__all__.append("popen4")

import copy_reg as _copy_reg

def _make_stat_result(tup, dict):
return stat_result(tup, dict)

def _pickle_stat_result(sr):
(type, args) = sr.__reduce__()
return (_make_stat_result, args)

try:
_copy_reg.pickle(stat_result, _pickle_stat_result, _make_stat_result)
except NameError: # stat_result may not exist
pass

def _make_statvfs_result(tup, dict):
return statvfs_result(tup, dict)

def _pickle_statvfs_result(sr):
(type, args) = sr.__reduce__()
return (_make_statvfs_result, args)

try:
_copy_reg.pickle(statvfs_result, _pickle_statvfs_result,
_make_statvfs_result)
except NameError: # statvfs_result may not exist
pass


Codul 5
"""Constants/functions for interpreting results of os.stat() and os.lstat().

Suggested usage: from stat import *
"""

# XXX Strictly spoken, this module may have to be adapted for each POSIX
# implementation; in practice, however, the numeric constants used by
# stat() are almost universal (even for stat() emulations on non-UNIX
# systems like MS-DOS).

# Indices for stat struct members in tuple returned by os.stat()

ST_MODE = 0
ST_INO = 1
ST_DEV = 2
ST_NLINK = 3
ST_UID = 4
ST_GID = 5
ST_SIZE = 6
ST_ATIME = 7
ST_MTIME = 8
ST_CTIME = 9

# Extract bits from the mode

def S_IMODE(mode):
return mode & 07777

def S_IFMT(mode):
return mode & 0170000

# Constants used as S_IFMT() for various file types
# (not all are implemented on all systems)

S_IFDIR = 0040000
S_IFCHR = 0020000
S_IFBLK = 0060000
S_IFREG = 0100000
S_IFIFO = 0010000
S_IFLNK = 0120000
S_IFSOCK = 0140000

# Functions to test for each file type

def S_ISDIR(mode):
return S_IFMT(mode) == S_IFDIR

def S_ISCHR(mode):
return S_IFMT(mode) == S_IFCHR

def S_ISBLK(mode):
return S_IFMT(mode) == S_IFBLK

def S_ISREG(mode):
return S_IFMT(mode) == S_IFREG

def S_ISFIFO(mode):
return S_IFMT(mode) == S_IFIFO

def S_ISLNK(mode):
return S_IFMT(mode) == S_IFLNK

def S_ISSOCK(mode):
return S_IFMT(mode) == S_IFSOCK

# Names for permission bits

S_ISUID = 04000
S_ISGID = 02000
S_ENFMT = S_ISGID
S_ISVTX = 01000
S_IREAD = 00400
S_IWRITE = 00200
S_IEXEC = 00100
S_IRWXU = 00700
S_IRUSR = 00400
S_IWUSR = 00200
S_IXUSR = 00100
S_IRWXG = 00070
S_IRGRP = 00040
S_IWGRP = 00020
S_IXGRP = 00010
S_IRWXO = 00007
S_IROTH = 00004
S_IWOTH = 00002
S_IXOTH = 00001


Codul 6
"""Define names for all type symbols known in the standard interpreter.

Types that are part of optional modules (e.g. array) are not listed.
"""
from __future__ import generators

import sys

# Iterators in Python aren't a matter of type but of protocol. A large
# and changing number of builtin types implement *some* flavor of
# iterator. Don't check the type! Use hasattr to check for both
# "__iter__" and "next" attributes instead.

NoneType = type(None)
TypeType = type
ObjectType = object

IntType = int
LongType = long
FloatType = float
try:
ComplexType = complex
except NameError:
pass

StringType = str
try:
UnicodeType = unicode
StringTypes = (StringType, UnicodeType)
except NameError:
StringTypes = (StringType,)

BufferType = type(buffer(''))

TupleType = tuple
ListType = list
DictType = DictionaryType = dict

def _f(): pass
FunctionType = type(_f)
LambdaType = type(lambda: None) # Same as FunctionType
try:
CodeType = type(_f.func_code)
except RuntimeError:
# Execution in restricted environment
pass

def g():
yield 1
GeneratorType = type(g())
del g

class _C:
def _m(self): pass
ClassType = type(_C)
UnboundMethodType = type(_C._m) # Same as MethodType
_x = _C()
InstanceType = type(_x)
MethodType = type(_x._m)

BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append) # Same as BuiltinFunctionType

ModuleType = type(sys)
FileType = file
XRangeType = type(xrange(0))

try:
raise TypeError
except TypeError:
try:
tb = sys.exc_info()[2]
TracebackType = type(tb)
FrameType = type(tb.tb_frame)
except AttributeError:
# In the restricted environment, exc_info returns (None, None,
# None) Then, tb.tb_frame gives an attribute error
pass
tb = None; del tb

SliceType = type(slice(0))
EllipsisType = type(Ellipsis)

DictProxyType = type(TypeType.__dict__)

del sys, _f, _C, _x, generators # Not for export


Codul 7
"""A more or less complete user-defined wrapper around dictionary objects."""

class UserDict:
def __init__(self, dict=None):
self.data = {}
if dict is not None: self.update(dict)
def __repr__(self): return repr(self.data)
def __cmp__(self, dict):
if isinstance(dict, UserDict):
return cmp(self.data, dict.data)
else:
return cmp(self.data, dict)
def __len__(self): return len(self.data)
def __getitem__(self, key): return self.data[key]
def __setitem__(self, key, item): self.data[key] = item
def __delitem__(self, key): del self.data[key]
def clear(self): self.data.clear()
def copy(self):
if self.__class__ is UserDict:
return UserDict(self.data)
import copy
data = self.data
try:
self.data = {}
c = copy.copy(self)
finally:
self.data = data
c.update(self)
return c
def keys(self): return self.data.keys()
def items(self): return self.data.items()
def iteritems(self): return self.data.iteritems()
def iterkeys(self): return self.data.iterkeys()
def itervalues(self): return self.data.itervalues()
def values(self): return self.data.values()
def has_key(self, key): return self.data.has_key(key)
def update(self, dict):
if isinstance(dict, UserDict):
self.data.update(dict.data)
elif isinstance(dict, type(self.data)):
self.data.update(dict)
else:
for k, v in dict.items():
self[k] = v
def get(self, key, failobj=None):
if not self.has_key(key):
return failobj
return self[key]
def setdefault(self, key, failobj=None):
if not self.has_key(key):
self[key] = failobj
return self[key]
def popitem(self):
return self.data.popitem()
def __contains__(self, key):
return key in self.data

class IterableUserDict(UserDict):
def __iter__(self):
return iter(self.data)
Imagine

Deconectat
Avatar utilizator
[Brahma]
Super Moderator
Super Moderator
Mesaje: 714
Membru din: 16 Mai 2017
Localitate: Adjud
Reputație: ®
♔[Super Moderator]✓
♔[Membru Club P]✓
♔[Mister J4M]
☬[Fost]: Moderator (3/3)☆
☬[Fost]: Trial Moderator (1/1)☆
Status: Ocupat!
Server Metin2: Nu exista
Mulțumiri acordate: 0
Mulțumiri primite: 73
Contact:

Re: Ce reprezinta codul? [PYTHON]

Mesajde [Brahma] » 03 Sep 2018, 16:39

Dacă în 3 zile autorul subiectului nu va da niciun semn de viata în topic, subiectul va fi trimis în Arhivă.


Înapoi la “Arhivă”

Cine este conectat

Utilizatori ce ce navighează pe acest forum: Niciun utilizator înregistrat și 3 vizitatori