The Python sys library provides access to some variables used or maintained by the interpreter used to manipulate the Python run time environment.
Once you’re done with this guide you’ll find that sys library has functions that are very useful in learning more about your user’s PC. When distributing applications you need to write code specific to
Python sys is part of Python’s standard library, hence it does not need to be downloaded separately. A simple
import sys statement is all that’s required.
This is a function that comes in handy when you want to terminate the whole process (A process is a program being executed). Similar to how a return statement terminates a function, the
exit() will shut down the whole program.
import sys import time inp = input("Input a Positive Number") if int(inp) < 0: print("Number less than 0") time.sleep(1) sys.exit()
An integer giving the maximum value a variable of type
Py_ssize_t can take. It’s usually
2**31 - 1 on a 32-bit platform and
2**63 - 1 on a 64-bit platform.
size = sys.maxsize print(size)
Returns a list of strings that specifies the search path for modules (Environmental variables). When downloading a library if your python.exe path is included in one these file paths, you do not need to specify the full python.exe file. This is because python automatically checks these search paths when run.
paths = sys.path print(paths)
The first string in the list will be the file path of the python script that is being executed. Also known as
A string containing the version number of the Python interpreter plus additional information on the build number and compiler used.
version = sys.version print(version)
3.7.4 (tags/v3.7.4:e07359572e, Jul 8 2018, 20:34:20) [MSC v.1916 64 bit (AMD64)]
Used to determine the operating system (platform) of the PC the script is being run on. A handy tool when distributing software on a wide range on Devices. Not all libraries and code work across all operating systems, so you’ll often have to write different code for different OS’s. See the example below to see how to effectively handle such a situation.
if sys.platform.startswith('freebsd'): # FreeBSD-specific code here... elif sys.platform.startswith('linux'): # Linux-specific code here... elif sys.platform.startswith('aix'): # AIX-specific code here...
A list of operating systems and the values they hold in Python..
Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. Follow this link to the main Recursion article to learn what recursion is.
Use this link to head back to the main Python Libraries article: link