Notas de Luis

Python

Entorno de trabajo

Crear

  python3 -m venv /path/to/new/virtual/environment
  python -m pip install --user --upgrade pip

Usar

  source <venv>/bin/activate
  deactivate

Instalar paquete

  # Download and unzip
  pip install requests
  pip install -r requirements.txt

Freezing dependencies

  pip freeze # To create requirements.txt

TYPES:

Text Type str (single line strings or multiline strings “”“)
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
None Type NoneType
  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered and changeable. No duplicate members.
Ordered Changeable Indexed Allow duplicates
List YES YES YES YES
Tuple YES NO YES YES
Set NO NO NO YES
Dicionary YES YES YES NO
  x = ["apple", "banana", "cherry"]   # list
  x = ("apple", "banana", "cherry")   # tuple
  x = range(6)                        # range
  x = {"name" : "John", "age" : 36}   # dict
  x = {"apple", "banana", "cherry"}   # set
  x = frozenset({"apple", "banana", "cherry"})  # frozenset

Casting:

  x = str("Hello World")      str
  x = int(20) int
  x = float(20.5)     float
  x = complex(1j)     complex
  x = list(("apple", "banana", "cherry"))     list
  x = tuple(("apple", "banana", "cherry"))    tuple
  x = range(6)        range
  x = dict(name="John", age=36)       dict
  x = set(("apple", "banana", "cherry"))      set
  x = frozenset(("apple", "banana", "cherry"))        frozenset
  x = bool(5) bool
  x = bytes(5)        bytes
  x = bytearray(5)    bytearray
  x = memoryview(bytes(5)) memoryview

Strings can be used as arrays:

  a = "Hello, World!"
  print(a[1])
  for x in "banana":
      print(x)
  b = "Hello, World!"
  print(b[2:5])
  print(b[:5])
  print(b[2:])
  print(b[-5:-2])

Check string:

  txt = "The best things in life are free!"
  print("free" in txt)
  txt = "The best things in life are free!"
  if "free" in txt:
      print("Yes, 'free' is present.")

Builtin functions

Función Uso
abs() Returns the absolute value of a number
all() Returns True if all items in an iterable object are true
any() Returns True if any item in an iterable object is true
ascii() Returns a readable version of an object. Replaces none-ascii characters with escape character
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
chr() Returns a character from the specified Unicode code.
classmethod() Converts a method into a class method
compile() Returns the specified source as an object, ready to be executed
complex() Returns a complex number
delattr() Deletes the specified attribute (property or method) from the specified object
dict() Returns a dictionary (Array)
dir() Returns a list of the specified object’s properties and methods
divmod() Returns the quotient and the remainder when argument1 is divided by argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
filter() Use a filter function to exclude items in an iterable object
float() Returns a floating point number
format() Formats a specified value
frozenset() Returns a frozenset object
getattr() Returns the value of the specified attribute (property or method)
globals() Returns the current global symbol table as a dictionary
hasattr() Returns True if the specified object has the specified attribute (property/method)
hash() Returns the hash value of a specified object
help() Executes the built-in help system
hex() Converts a number into a hexadecimal value
id() Returns the id of an object
input() Allowing user input
int() Returns an integer number
isinstance() Returns True if a specified object is an instance of a specified object
issubclass() Returns True if a specified class is a subclass of a specified object
iter() Returns an iterator object
len() Returns the length of an object
list() Returns a list
locals() Returns an updated dictionary of the current local symbol table
map() Returns the specified iterator with the specified function applied to each item
max() Returns the largest item in an iterable
memoryview() Returns a memory view object
min() Returns the smallest item in an iterable
next() Returns the next item in an iterable
object() Returns a new object
oct() Converts a number into an octal
open() Opens a file and returns a file object
ord() Convert an integer representing the Unicode of the specified character
pow() Returns the value of x to the power of y
print() Prints to the standard output device
property() Gets, sets, deletes a property
range() Returns a sequence of numbers, starting from 0 and increments by 1 (by default)
repr() Returns a readable version of an object
reversed() Returns a reversed iterator
round() Rounds a numbers
set() Returns a new set object
setattr() Sets an attribute (property/method) of an object
slice() Returns a slice object
sorted() Returns a sorted list
staticmethod() Converts a method into a static method
str() Returns a string object
sum() Sums the items of an iterator
super() Returns an object that represents the parent class
tuple() Returns a tuple
type() Returns the type of an object
vars() Returns the \_\_dict\_\_ property of an object
zip() Returns an iterator, from two or more iterators

List methods

Función Uso
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
iappend() Adds an element at the end of the list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Dictionary methods

Función Uso
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary’s keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary

File methods

Función Uso
close() Closes the file
detach() Returns the separated raw stream from the buffer
fileno() Returns a number that represents the stream, from the operating system’s perspective
flush() Flushes the internal buffer
isatty() Returns whether the file stream is interactive or not
read() Returns the file content
readable() Returns whether the file stream can be read or not
readline() Returns one line from the file
readlines() Returns a list of lines from the file
seek() Change the file position
seekable() Returns whether the file allows us to change the file position
tell() Returns the current file position
truncate() Resizes the file to a specified size
writable() Returns whether the file can be written to or not
write() Writes the specified string to the file
writelines() Writes a list of strings to the file

String methods

Función Uso
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format\_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Format

  age = 36
  txt = "My name is John, and I am {}"
  print(txt.format(age))
  
  quantity = 3
  itemno = 567
  price = 49.95
  myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
  print(myorder.format(quantity, itemno, price))
  
  return f"{self.name}({self.age})"
  
  print(f"asdfdfsas {}")

Clases & objects

  class Person:
      def __init__(self, fname, lname, age):
          self.firstname = fname
          self.lastname = lname
          self.age = age
      def __str__(self):
          return f"{self.firstname}({self.age})"
      def printname(self):
          print(self.firstname, self.lastname)
  p1 = Person("John", "Smith", 36)
  print(p1)
  p1.printname()
  del p1
  
  class Student(Person): # Herencia
      def __init__(self, fname, lname, age):
          super().__init__(self, fname, lname, age)
          self.graduationyear = 2019

Error handling

  try:
      print(x)
  except NameError:
      print("Variable x is not defined")
  except:
      print("An exception occurred")
  else:
      print("Nothing went wrong")
  
  raise Exception("Sorry, no numbers below zero")
  raise TypeError("Only integers are allowed")

Exceptions

Función Uso
ArithmeticError Raised when an error occurs in numeric calculations
AssertionError Raised when an assert statement fails
AttributeError Raised when attribute reference or assignment fails
Exception Base class for all exceptions
EOFError Raised when the input() method hits an “end of file” condition (EOF)
FloatingPointError Raised when a floating point calculation fails
GeneratorExit Raised when a generator is closed (with the close() method)
ImportError Raised when an imported module does not exist
IndentationError Raised when indentation is not correct
IndexError Raised when an index of a sequence does not exist
KeyError Raised when a key does not exist in a dictionary
KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete
LookupError Raised when errors raised cant be found
MemoryError Raised when a program runs out of memory
NameError Raised when a variable does not exist
NotImplementedError Raised when an abstract method requires an inherited class to override the method
OSError Raised when a system related operation causes an error
OverflowError Raised when the result of a numeric calculation is too large
ReferenceError Raised when a weak reference object does not exist
RuntimeError Raised when an error occurs that do not belong to any specific exceptions
StopIteration Raised when the next() method of an iterator has no further values
SyntaxError Raised when a syntax error occurs
TabError Raised when indentation consists of tabs or spaces
SystemError Raised when a system error occurs
SystemExit Raised when the sys.exit() function is called
TypeError Raised when two different types are combined
UnboundLocalError Raised when a local variable is referenced before assignment
UnicodeError Raised when a unicode problem occurs
UnicodeEncodeError Raised when a unicode encoding problem occurs
UnicodeDecodeError Raised when a unicode decoding problem occurs
UnicodeTranslateError Raised when a unicode translation problem occurs
ValueError Raised when there is a wrong value in a specified data type
ZeroDivisionError Raised when the second operator in a division is zero

os module

Función Uso
WCOREDUMP(status): Return True if the process returning status was dumped to a core file.
WEXITSTATUS(status): Return the process return code from status.
WIFCONTINUED(status): Return True if a particular process was continued from a job control stop.
WIFEXITED(status): Return True if the process returning status exited via the exit() system call.
WIFSIGNALED(status): Return True if the process returning status was terminated by a signal.
WIFSTOPPED(status): Return True if the process returning status was stopped.
WSTOPSIG(status): Return the signal that stopped the process that provided the status value.
WTERMSIG(status): Return the signal that terminated the process that provided the status value.
\_exit(status): Exit to the system with specified status, without normal exit processing.
abort(): Abort the interpreter immediately.
access(path, mode, \*, dir\_fd=None, effective\_ids=False, follow\_symlinks=True): Use the real uid/gid to test for access to a path.
chdir(path): Change the current working directory to the specified path.
chmod(path, mode, \*, dir\_fd=None, follow\_symlinks=True): Change the access permissions of a file.
chown(path, uid, gid, \*, dir\_fd=None, follow\_symlinks=True): Change the owner and group id of path to the numeric uid and gid.
chroot(path): Change root directory to path.
close(fd): Close a file descriptor.
closerange(fd\_low, fd\_high): Closes all file descriptors in \[fd\_low, fd\_high), ignoring errors.
confstr(name): Return a string-valued system configuration variable.
copy\_file\_range(src, dst, count, offset\_src=None, offset\_dst=None): Copy count bytes from one file descriptor to another.
cpu\_count(): Return the number of CPUs in the system; return None if indeterminable.
ctermid(): Return the name of the controlling terminal for this process.
device\_encoding(fd): Return a string describing the encoding of a terminal’s file descriptor.
dup(fd): Return a duplicate of a file descriptor.
dup2(fd, fd2, inheritable=True): Duplicate file descriptor.
eventfd(initval, flags=524288): Creates and returns an event notification file descriptor.
eventfd\_read(fd): Read eventfd value
eventfd\_write(fd, value): Write eventfd value.
execl(file, \*args): execl(file, \*args)
execle(file, \*args): execle(file, \*args, env)
execlp(file, \*args): execlp(file, \*args)
execlpe(file, \*args): execlpe(file, \*args, env)
execv(path, argv): Execute an executable path with arguments, replacing current process.
execve(path, argv, env): Execute an executable path with arguments, replacing current process.
execvp(file, args): execvp(file, args)
execvpe(file, args, env): execvpe(file, args, env)
fchdir(fd): Change to the directory of the given file descriptor.
fchmod(fd, mode): Change the access permissions of the file given by file descriptor fd.
fchown(fd, uid, gid): Change the owner and group id of the file specified by file descriptor.
fdatasync(fd): Force write of fd to disk without forcing update of metadata.
fdopen(fd, mode=‘r’, buffering=-1, encoding=None, \*args, \*\*kwargs)
fork(): Fork a child process.
forkpty(): Fork a new process with a new pseudo-terminal as controlling tty.
fpathconf(fd, name): Return the configuration limit name for the file descriptor fd.
fsdecode(filename): Decode filename (an os.PathLike, bytes, or str) from the filesystem
fsencode(filename): Encode filename (an os.PathLike, bytes, or str) to the filesystem
fspath(path): Return the file system path representation of the object.
fstat(fd): Perform a stat system call on the given file descriptor.
fstatvfs(fd): Perform an fstatvfs system call on the given fd.
fsync(fd): Force write of fd to disk.
ftruncate(fd, length): Truncate a file, specified by file descriptor, to a specific length.
fwalk(top=‘.’, topdown=True,onerror=None,\*,follow\_symlinks=False, dir\_fd=None): Directory tree generator.
get\_blocking(fd): Get the blocking mode of the file descriptor.
get\_exec\_path(env=None): Returns the sequence of directories that will be searched for the
get\_inheritable(fd): Get the close-on-exe flag of the specified file descriptor.
get\_terminal\_size(…): Return the size of the terminal window as (columns, lines).
getcwd(): Return a unicode string representing the current working directory.
getcwdb(): Return a bytes string representing the current working directory.
getegid(): Return the current process’s effective group id.
getenv(key, default=None): Get an environment variable, return None if it doesn’t exist.
getenvb(key, default=None): Get an environment variable, return None if it doesn’t exist.
geteuid(): Return the current process’s effective user id.
getgid(): Return the current process’s group id.
getgrouplist(user, group): Returns a list of groups to which a user belongs.
getgroups(): Return list of supplemental group IDs for the process.
getloadavg(): Return average recent system load information.
getlogin(): Return the actual login name.
getpgid(pid): Call the system call getpgid(), and return the result.
getpgrp(): Return the current process group id.
getpid(): Return the current process id.
getppid(): Return the parent’s process id.
getpriority(which, who): Return program scheduling priority.
getrandom(size, flags=0): Obtain a series of random bytes.
getresgid(): Return a tuple of the current process’s real, effective, and saved group ids.
getresuid(): Return a tuple of the current process’s real, effective, and saved user ids.
getsid(pid): Call the system call getsid(pid) and return the result.
getuid(): Return the current process’s user id.
getxattr(path, attribute, \*, follow\_symlinks=True): Return the value of extended attribute attribute on path.
initgroups(username, gid): Initialize the group access list.
isatty(fd): Return True if the fd is connected to a terminal.
kill(pid, signal): Kill a process with a signal.
killpg(pgid, signal): Kill a process group with a signal.
lchown(path, uid, gid): Change the owner and group id of path to the numeric uid and gid.
link(src, dst, \*, src\_dir\_fd=None, dst\_dir\_fd=None, follow\_symlinks=True): Create a hard link to a file.
listdir(path=None): Return a list containing the names of the files in the directory.
listxattr(path=None, \*, follow\_symlinks=True): Return a list of extended attributes on path.
lockf(fd, command, length): Apply, test or remove a POSIX lock on an open file descriptor.
lseek(fd, position, how): Set the position of a file descriptor. Return the new position.
lstat(path, \*, dir\_fd=None): Perform a stat system call on the given path, without following symbolic links.
major(device): Extracts a device major number from a raw device number.
makedev(major, minor): Composes a raw device number from the major and minor device numbers.
makedirs(name, mode=511, exist\_ok=False): makedirs(name \[, mode=0o777\]\[, exist\_ok=False\])
memfd\_create(name, flags=1)
minor(device): Extracts a device minor number from a raw device number.
mkdir(path, mode=511, \*, dir\_fd=None): Create a directory.
mkfifo(path, mode=438, \*, dir\_fd=None): Create a “fifo” (a POSIX named pipe).
mknod(path, mode=384, device=0, \*, dir\_fd=None): Create a node in the file system.
nice(increment): Add increment to the priority of process and return the new priority.
open(path, flags, mode=511, \*, dir\_fd=None): Open a file for low level IO. Returns a file descriptor (integer).
openpty(): Open a pseudo-terminal.
pathconf(path, name): Return the configuration limit name for the file or directory path.
pidfd\_open(pid, flags=0): Return a file descriptor referring to the process *pid*.
pipe(): Create a pipe.
pipe2(flags): Create a pipe with flags set atomically.
popen(cmd, mode=‘r’, buffering=-1)
posix\_fadvise(fd, offset, length, advice): Announce an intention to access data in a specific pattern.
posix\_fallocate(fd, offset, length): Ensure a file has allocated at least a particular number of bytes on disk.
posix\_spawn(…): Execute the program specified by path in a new process.
posix\_spawnp(…): Execute the program specified by path in a new process.
pread(fd, length, offset): Read a number of bytes from a file descriptor starting at a particular offset.
preadv(fd, buffers, offset, flags=0): Reads from a file descriptor into a number of mutable bytes-like objects.
putenv(name, value): Change or add an environment variable.
pwrite(fd, buffer, offset): Write bytes to a file descriptor starting at a particular offset.
pwritev(fd, buffers, offset, flags=0): Writes the contents of bytes-like objects to a file descriptor at a given offset.
read(fd, length): Read from a file descriptor. Returns a bytes object.
readlink(path, \*, dir\_fd=None): Return a string representing the path to which the symbolic link points.
readv(fd, buffers): Read from a file descriptor fd into an iterable of buffers.
register\_at\_fork(…): Register callables to be called when forking a new process.
remove(path, \*, dir\_fd=None): Remove a file (same as unlink()).
removedirs(name): removedirs(name)
removexattr(path, attribute, \*, follow\_symlinks=True): Remove extended attribute attribute on path.
rename(src, dst, \*, src\_dir\_fd=None, dst\_dir\_fd=None): Rename a file or directory.
renames(old, new): renames(old, new)
replace(src, dst, \*, src\_dir\_fd=None, dst\_dir\_fd=None): Rename a file or directory, overwriting the destination.
rmdir(path, \*, dir\_fd=None): Remove a directory.
scandir(path=None): Return an iterator of DirEntry objects for given path.
sched\_get\_priority\_max(policy): Get the maximum scheduling priority for policy.
sched\_get\_priority\_min(policy): Get the minimum scheduling priority for policy.
sched\_getaffinity(pid): Return the affinity of the process identified by pid (or the current process if zero).
sched\_getparam(pid): Returns scheduling parameters for the process identified by pid.
sched\_getscheduler(pid): Get the scheduling policy for the process identified by pid.
sched\_rr\_get\_interval(pid): Return the round-robin quantum for the process identified by pid, in seconds.
sched\_setaffinity(pid, mask): Set the CPU affinity of the process identified by pid to mask.
sched\_setparam(pid, param): Set scheduling parameters for the process identified by pid.
sched\_setscheduler(pid, policy, param): Set the scheduling policy for the process identified by pid.
sched\_yield(): Voluntarily relinquish the CPU.
sendfile(out\_fd, in\_fd, offset, count): Copy count bytes from file descriptor in\_fd to file descriptor out\_fd.
set\_blocking(fd, blocking): Set the blocking mode of the specified file descriptor.
set\_inheritable(fd, inheritable): Set the inheritable flag of the specified file descriptor.
setegid(egid): Set the current process’s effective group id.
seteuid(euid): Set the current process’s effective user id.
setgid(gid): Set the current process’s group id.
setgroups(groups): Set the groups of the current process to list.
setpgid(pid, pgrp): Call the system call setpgid(pid, pgrp).
setpgrp(): Make the current process the leader of its process group.
setpriority(which, who, priority): Set program scheduling priority.
setregid(rgid, egid): Set the current process’s real and effective group ids.
setresgid(rgid, egid, sgid): Set the current process’s real, effective, and saved group ids.
setresuid(ruid, euid, suid): Set the current process’s real, effective, and saved user ids.
setreuid(ruid, euid): Set the current process’s real and effective user ids.
setsid(): Call the system call setsid().
setuid(uid): Set the current process’s user id.
setxattr(path, attribute, value, flags=0, \*, follow\_symlinks=True): Set extended attribute attribute on path to value.
spawnl(mode, file, \*args): spawnl(mode, file, \*args) -\> integer
spawnle(mode, file, \*args): spawnle(mode, file, \*args, env) -\> integer
spawnlp(mode, file, \*args): spawnlp(mode, file, \*args) -\> integer
spawnlpe(mode, file, \*args): spawnlpe(mode, file, \*args, env) -\> integer
spawnv(mode, file, args): spawnv(mode, file, args) -\> integer
spawnve(mode, file, args, env): spawnve(mode, file, args, env) -\> integer
spawnvp(mode, file, args): spawnvp(mode, file, args) -\> integer
spawnvpe(mode, file, args, env): spawnvpe(mode, file, args, env) -\> integer
splice(src, dst, count, offset\_src=None, offset\_dst=None, flags=0): Transfer count bytes from one pipe to a descriptor or vice versa.
stat(path, \*, dir\_fd=None, follow\_symlinks=True): Perform a stat system call on the given path.
statvfs(path): Perform a statvfs system call on the given path.
strerror(code): Translate an error code to a message string.
symlink(src, dst, target\_is\_directory=False, \*, dir\_fd=None): Create a symbolic link pointing to src named dst.
sync(): Force write of everything to disk.
sysconf(name): Return an integer-valued system configuration variable.
system(command): Execute the command in a subshell.
tcgetpgrp(fd): Return the process group associated with the terminal specified by fd.
tcsetpgrp(fd, pgid): Set the process group associated with the terminal specified by fd.
times(): Return a collection containing process timing information.
truncate(path, length): Truncate a file, specified by path, to a specific length.
ttyname(fd): Return the name of the terminal device connected to ‘fd’.
umask(mask): Set the current numeric umask and return the previous umask.
uname(): Return an object identifying the current operating system.
unlink(path, \*, dir\_fd=None): Remove a file (same as remove()).
unsetenv(name): Delete an environment variable.
urandom(size): Return a bytes object containing random bytes suitable for cryptographic use.
utime(…): Set the access and modified time of path.
wait(): Wait for completion of a child process.
wait3(options): Wait for completion of a child process.
wait4(pid, options): Wait for completion of a specific child process.
waitid(idtype, id, options): Returns the result of waiting for a process or processes.
waitpid(pid, options): Wait for completion of a given child process.
waitstatus\_to\_exitcode(status): Convert a wait status to an exit code.
walk(top, topdown=True, onerror=None, followlinks=False): Directory tree generator.
write(fd, data): Write a bytes object to a file descriptor.
writev(fd, buffers): Iterate over buffers, and write the contents of each to a file descriptor.

sys Module

Definitions

Función Uso
argv command line arguments; argv\[0\] is the script pathname if known
path module search path; path\[0\] is the script directory, else ’’
modules dictionary of loaded modules
displayhook called to show results in an interactive session
excepthook called to handle any uncaught exception other than SystemExit
stdin standard input file object; used by input()
stdout standard output file object; used by print()
stderr standard error object; used for error messages
last\_type type of last uncaught exception
last\_value value of last uncaught exception
last\_traceback traceback of last uncaught exception
builtin\_module\_names tuple of module names built into this interpreter
copyright copyright notice pertaining to this interpreter
exec\_prefix prefix used to find the machine-specific Python library
executable absolute path of the executable binary of the Python interpreter
float\_info a named tuple with information about the float implementation.
float\_repr\_style string indicating the style of repr() output for floats
hash\_info a named tuple with information about the hash algorithm.
hexversion version information encoded as a single integer
implementation Python implementation information.
int\_info a named tuple with information about the int implementation.
maxsize the largest supported length of containers.
maxunicode the value of the largest Unicode code point
platform platform identifier
prefix prefix used to find the Python library
thread\_info a named tuple with information about the thread implementation.
version the version of this interpreter as a string
version\_info version information as a named tuple
\_\_stdin\_\_ the original stdin; don’t touch\!
\_\_stdout\_\_ the original stdout; don’t touch\!
\_\_stderr\_\_ the original stderr; don’t touch\!
\_\_displayhook\_\_ the original displayhook; don’t touch\!
\_\_excepthook\_\_ the original excepthook; don’t touch\!

Functions:

Función Uso
addaudithook(hook)
audit(…)
breakpointhook(…)
call\_tracing(func, args)
displayhook() print an object to the screen, and save it in builtins.\_
excepthook() print an exception and its traceback to sys.stderr
exc\_info() return thread-safe information about the current exception
exit() exit the interpreter by raising SystemExit
exit(status=None)
getallocatedblocks()
get\_asyncgen\_hooks()
get\_coroutine\_origin\_tracking\_depth()
getdefaultencoding()
getdlopenflags() returns flags to be used for dlopen() calls
getfilesystemencodeerrors()
getfilesystemencoding()
getprofile() get the global profiling function
getrecursionlimit() return the max recursion depth for the interpreter
getrefcount() return the reference count for an object (plus one :-)
getrefcount(object)
getsizeof() return the size of an object in bytes
getswitchinterval()
gettrace() get the global debug tracing function
intern(string)
is\_finalizing()
set\_asyncgen\_hooks(…)
set\_coroutine\_origin\_tracking\_depth(depth)
setdlopenflags() set the flags to be used for dlopen() calls
setprofile() set the global profiling function
setrecursionlimit() set the max recursion depth for the interpreter
setswitchinterval(interval)
settrace() set the global debug tracing function
unraisablehook(unraisable)

Modules

Función Uso
\_\_future\_\_ Future statement definitions
\_\_main\_\_ The environment where top-level code is run. Covers command-line interfaces, import-time behavior, and \name == '\main'.
\_thread Low-level threading API.
abc Abstract base classes according to :pep:3119.
argparse Command-line option and argument parsing library.
array Space efficient arrays of uniformly typed numeric values.
ast Abstract Syntax Tree classes and manipulation.
asyncio Asynchronous I/O.
atexit Register and execute cleanup functions.
base64 RFC 4648: Base16, Base32, Base64 Data Encodings; Base85 and Ascii85
bdb Debugger framework.
binascii Tools for converting between binary and various ASCII-encoded
binary representations.
bisect Array bisection algorithms for binary searching.
builtins The module that provides the built-in namespace.
bz2 Interfaces for bzip2 compression and decompression.
calendar Functions for working with calendars, including some emulation
of the Unix cal program.
cmath Mathematical functions for complex numbers.
cmd Build line-oriented command interpreters.
code Facilities to implement read-eval-print loops.
codecs Encode and decode data and streams.
codeop Compile (possibly incomplete) Python code.
collections Container datatypes
colorsys Conversion functions between RGB and other color systems.
compileall Tools for byte-compiling all Python source files in a directory tree.
concurrent
configparser Configuration file parser.
contextlib Utilities for with-statement contexts.
contextvars Context Variables
copy Shallow and deep copy operations.
copyreg Register pickle support functions.
cProfile
csv Write and read tabular data to and from delimited files.
ctypes A foreign function library for Python.
curses (Unix) An interface to the curses library, providing portable terminal handling.
dataclasses Generate special methods on user-defined classes.
datetime Basic date and time types.
dbm Interfaces to various Unix “database” formats.
decimal Implementation of the General Decimal Arithmetic Specification.
difflib Helpers for computing differences between objects.
dis Disassembler for Python bytecode.
distutils Support for building and installing Python modules into an existing Python installation.
doctest Test pieces of code within docstrings.
email Package supporting the parsing, manipulating, and generating email messages.
encodings
ensurepip Bootstrapping the “pip” installer into an existing Python installation or virtual environment.
enum Implementation of an enumeration class.
errno Standard errno system symbols.
faulthandler Dump the Python traceback.
fcntl (Unix) The fcntl() and ioctl() system calls.
filecmp Compare files efficiently.
fileinput Loop over standard input or a list of files.
fnmatch Unix shell style filename pattern matching.
fractions Rational numbers.
ftplib FTP protocol client (requires sockets).
functools Higher-order functions and operations on callable objects.
gc Interface to the cycle-detecting garbage collector.
getopt Portable parser for command line options; support both short and long option names.
getpass Portable reading of passwords and retrieval of the userid.
gettext Multilingual internationalization services.
glob Unix shell style pathname pattern expansion.
graphlib Functionality to operate with graph-like structures
grp (Unix) The group database (getgrnam() and friends).
gzip Interfaces for gzip compression and decompression using file objects.
hashlib Secure hash and message digest algorithms.
heapq Heap queue algorithm (a.k.a. priority queue).
hmac Keyed-Hashing for Message Authentication (HMAC) implementation
html Helpers for manipulating HTML.
http HTTP status codes and messages
idlelib Implementation package for the IDLE shell/editor.
imaplib IMAP4 protocol client (requires sockets).
importlib The implementation of the import machinery.
inspect Extract information and source code from live objects.
io Core tools for working with streams.
ipaddress IPv4/IPv6 manipulation library.
itertools Functions creating iterators for efficient looping.
json Encode and decode the JSON format.
keyword Test whether a string is a keyword in Python.
lib2to3 The 2to3 library
linecache Provides random access to individual lines from text files.
locale Internationalization services.
logging Flexible event logging system for applications.
lzma A Python wrapper for the liblzma compression library.
mailbox Manipulate mailboxes in various formats
marshal Convert Python objects to streams of bytes and back (with different constraints).
math Mathematical functions (sin() etc.).
mimetypes Mapping of filename extensions to MIME types.
mmap Interface to memory-mapped files for Unix and Windows.
modulefinder Find modules used by a script.
msvcrt (Windows) Miscellaneous useful routines from the MS VC++ runtime.
multiprocessing Process-based parallelism.
netrc Loading of .netrc files.
numbers Numeric abstract base classes (Complex, Real, Integral, etc.).
operator Functions corresponding to the standard operators.
os Miscellaneous operating system interfaces.
pathlib Object-oriented filesystem paths
pdb The Python debugger for interactive interpreters.
pickle Convert Python objects to streams of bytes and back.
pickletools Contains extensive comments about the pickle protocols and pickle-machine opcodes, as well as some useful functions.
pkgutil Utilities for the import system.
platform Retrieves as much platform identifying data as possible.
plistlib Generate and parse Apple plist files.
poplib POP3 protocol client (requires sockets).
posix (Unix) The most common POSIX system calls (normally used via module os).
pprint Data pretty printer.
profile Python source profiler.
pstats Statistics object for use with the profiler.
pty (Unix) Pseudo-Terminal Handling for Unix.
pwd (Unix) The password database (getpwnam() and friends).
py\_compile Generate byte-code files from Python source files.
pyclbr Supports information extraction for a Python module browser.
pydoc Documentation generator and online help system.
queue A synchronized queue class.
quopri Encode and decode files using the MIME quoted-printable encoding.
random Generate pseudo-random numbers with various common distributions.
re Regular expression operations.
readline (Unix) GNU readline support for Python.
reprlib Alternate repr() implementation with size limits.
resource (Unix) An interface to provide resource usage information on the current process.
rlcompleter Python identifier completion, suitable for the GNU readline library.
runpy Locate and run Python modules without importing them first.
sched General purpose event scheduler.
secrets Generate secure random numbers for managing secrets.
select Wait for I/O completion on multiple streams.
selectors High-level I/O multiplexing.
shelve Python object persistence.
shlex Simple lexical analysis for Unix shell-like languages.
shutil High-level file operations, including copying.
signal Set handlers for asynchronous events.
site Module responsible for site-specific configuration.
smtplib SMTP protocol client (requires sockets).
socket Low-level networking interface.
socketserver A framework for network servers.
sqlite3 A DB-API 2.0 implementation using SQLite 3.x.
ssl TLS/SSL wrapper for socket objects
stat Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat().
statistics Mathematical statistics functions
string Common string operations.
stringprep String preparation, as per RFC 3453
struct Interpret bytes as packed binary data.
subprocess Subprocess management.
symtable Interface to the compiler’s internal symbol tables.
sys Access system-specific parameters and functions.
sysconfig Python’s configuration information
syslog (Unix) An interface to the Unix syslog library routines.
tabnanny Tool for detecting white space related problems in Python source files in a directory tree.
tarfile Read and write tar-format archive files.
tempfile Generate temporary files and directories.
termios (Unix) POSIX style tty control.
test Regression tests package containing the testing suite for Python.
textwrap Text wrapping and filling
threading Thread-based parallelism.
time Time access and conversions.
timeit Measure the execution time of small code snippets.
tkinter Interface to Tcl/Tk for graphical user interfaces
token Constants representing terminal nodes of the parse tree.
tokenize Lexical scanner for Python source code.
tomllib Parse TOML files.
trace Trace or track Python statement execution.
traceback Print or retrieve a stack traceback.
tracemalloc Trace memory allocations.
tty (Unix) Utility functions that perform common terminal control operations.
turtle An educational framework for simple graphics applications
turtledemo A viewer for example turtle scripts
types Names for built-in types.
typing Support for type hints (see :pep:484).
unicodedata Access the Unicode Database.
unittest Unit testing framework for Python.
urllib
uuid UUID objects (universally unique identifiers) according to RFC 4122
venv Creation of virtual environments.
warnings Issue warning messages and control their disposition.
wave Provide an interface to the WAV sound format.
weakref Support for weak references and weak dictionaries.
webbrowser Easy-to-use controller for web browsers.
winreg (Windows) Routines and objects for manipulating the Windows registry.
winsound (Windows) Access to the sound-playing machinery for Windows.
wsgiref WSGI Utilities and Reference Implementation.
xml Package containing XML processing modules
xmlrpc
zipapp Manage executable Python zip archives
zipfile Read and write ZIP-format archive files.
zipimport Support for importing Python modules from ZIP archives.
zlib Low-level interface to compression and decompression routines compatible with gzip.
zoneinfo IANA time zone support

Module dataclasses

This module provides a decorator and functions for automatically adding generated special methods such as \_\_init\_\_(), eq() and \_\_repr\_\_() to user-defined classes.

  from dataclasses import dataclass
  @dataclass
  class InventoryItem:
      """Class for keeping track of an item in inventory."""
      name: str
      unit_price: float
      quantity_on_hand: int = 0
      x: int
      y: int = field(repr=False)
      z: int = field(repr=False, default=10)
      t: int = 20
      mylist: list = field(default_factory=list)
  
      def total_cost(self) -> float:
          return self.unit_price * self.quantity_on_hand

SQLite memory

import sqlite3   
try:
    sqlite_Connection = sqlite3.connect('temp.db')
    conn = sqlite3.connect(':memory:')
    print("\nMemory database created and connected to SQLite.")
    sqlite_select_Query = "select sqlite_version();"
    conn.execute(sqlite_select_Query)
    print("\nSQLite Database Version is: ", sqlite3.version)
    conn.close()
except sqlite3.Error as error:
    print("\nError while connecting to sqlite", error)
finally:
    if (sqlite_Connection):
        sqlite_Connection.close()
        print("\nThe SQLite connection is closed.")

SQLite disk

  import sqlite3
  from sqlite3 import Error
  
  def sql_connection():
      try:
          conn = sqlite3.connect('mydatabase.db')
          return conn
      except Error:
          print(Error)
  
  def sql_table(conn):
      cursorObj = conn.cursor()
      # Create the table
      cursorObj.execute("""
          CREATE TABLE salesman(salesman_id n(5), 
                                  name char(30), 
                                  city char(35), 
                                  commission decimal(7,2));
      """)
      # Insert records
      cursorObj.executescript("""
      INSERT INTO salesman VALUES(5001,'James Hoog', 'New York', 0.15);
      INSERT INTO salesman VALUES(5002,'Nail Knite', 'Paris', 0.25);
      INSERT INTO salesman VALUES(5003,'Pit Alex', 'London', 0.15);
      INSERT INTO salesman VALUES(5004,'Mc Lyon', 'Paris', 0.35);
      INSERT INTO salesman VALUES(5005,'Paul Adam', 'Rome', 0.45);
      """)
      conn.commit()
      cursorObj.execute("SELECT * FROM salesman")
      rows = cursorObj.fetchall()
      print("Agent details:")
      for row in rows:
          print(row)
          print("\nUpdate all commision to .55:")
      sql_update_query = """Update salesman set commission = .55"""
      cursorObj.execute(sql_update_query)
      conn.commit()
      print("Record Updated successfully ")
      cursorObj.execute("SELECT * FROM salesman")
      rows = cursorObj.fetchall()
      print("\nAfter updating Agent details:")
      for row in rows:
          print(row)
  sqllite_conn = sql_connection()
  sql_table(sqllite_conn)
  if (sqllite_conn):
      sqllite_conn.close()
      print("\nThe SQLite connection is closed.")

trick to debug

exc\_info = sys.exc\_info() print(’’.join(traceback.format\_exception(\*exc\_info)))

computing/coding/python/python.txt · Última modificación: por 127.0.0.1