Home Backend Development Python Tutorial Basic introduction to python sys module

Basic introduction to python sys module

Jun 14, 2019 pm 02:47 PM
python sys

1: sys is a built-in module of python.

Use the import statement to enter the sys module.

Related recommendations: "python Video"

Basic introduction to python sys module

When import sys is executed, python is listed in the directory in the sys.path variable Find the sys module file. Then run the statements in the main block of this module to initialize it, and then you can use the module.

2: Common functions of the sys module

You can use the dir() method to view the methods available in the module. The results are as follows. I have not used many of them, so I just keep them simple. Introduce several methods that I have used.

$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', '_mercurial', '_multiarch', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']
Copy after login

(1) sys.argv implements passing parameters from outside the program to the program

sys.argv variable is a string containing command line parameters List, use the command line to pass parameters to the program. Among them, the name of the script is always the first parameter in the sys.argv list.

(2) sys.path contains a list of directory names of input modules.

Get the string collection of the specified module search path. You can put the written module under a certain path, and you can find it correctly when importing in the program. When importing module_name, module.name is searched based on the path of sys.path. You can also customize the module path.

sys.path.append("Custom module path")

(3) sys.exit([arg]) Exit in the middle of the program, arg=0 means normal exit

Generally, the interpreter automatically exits when the execution reaches the end of the main program. However, if you need to exit the program midway, you can call the sys.exit function with an optional integer parameter returned to the calling program, indicating that you can The call to sys.exit is captured in the main program. (0 means normal exit, others are exceptions) Of course, you can also use string parameters to indicate unsuccessful error messages.

(4) sys.modules

sys.modules is a global dictionary, which is loaded in memory after python is started. Whenever a programmer imports a new module, sys.modules will automatically record the module. When the module is imported for the second time, Python will directly look it up in the dictionary, thus speeding up the program. It has all the methods that the dictionary has.

(5) sys.getdefaultencoding() / sys.setdefaultencoding() / sys.getfilesystemencoding()

sys.getdefaultencoding()

Get the current encoding of the system, which generally defaults to ascii.

sys.setdefaultencoding()

Set the system default encoding. You will not see this method when executing dir (sys). If the execution fails in the interpreter, you can execute reload (sys) first. , after executing setdefaultencoding('utf8'), the system default encoding is set to utf8. (See setting the system default encoding)

sys.getfilesystemencoding()

Get the encoding used by the file system. It returns 'mbcs' under Windows and 'utf-8' under mac

(6) sys.stdin, sys.stdout, sys.stderr

The stdin, stdout, and stderr variables contain stream objects corresponding to standard I/O streams. If you need better control over the output, and print doesn't meet your requirements, they are what you need. You can also replace them, and then you can redirect output and input to other devices (device), or process them in non-standard ways.

(7) sys.platform

Get the current system platform. Such as: win32, Linux, etc.

3: Example

(1) sys.argv sys.path

$ cat sys-test.py
 #!/usr/bin/python
import sys
print 'The command line arguments are:'
for i in sys.argv:
    print i
print '\n\nThe PYTHONPATH is', sys.path, '\n'
Copy after login

Run result:

$ python sys-test.py my name is ubuntu 
The command line arguments are:
sys-test.py
my
name
is
ubuntu
The PYTHONPATH is ['/work/python-practice', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client']
Copy after login

(2) sys.exit

import sys
def exitfunc(value):
    print (value)
    sys.exit(0)
print("hello")
try:
    sys.exit(90)
except SystemExit as value:
    exitfunc(value)   
print("come?")
Copy after login

Running results:

hello
90
Copy after login

The program first prints hello, then executes exit(90), throws an exception and passes 90 to values. Values ​​is executed in the passed function and prints 90. The program exits. The following "come?" will not be printed because it has already exited. If you remove sys.exit(0) in the exitfunc function at this time, the program will continue to execute until "come?" is output.

(3) sys.modules

sys.modules.keys() returns a list of all imported modules

keys is the module name

values ​​is the module

modules return path

import sys
print(sys.modules.keys())
print("**************************************************************************")
print(sys.modules.values())
print("**************************************************************************")
print(sys.modules["os"])
Copy after login

Run result:

['copy_reg', 'sre_compile', '_sre', 'encodings', 'site', '__builtin__', 'sysconfig', '__main__', 'encodings.encodings', 'abc', 'posixpath', '_weakrefset', 'errno', 'encodings.codecs', 'sre_constants', 're', '_abcoll', 'types', '_codecs', 'encodings.__builtin__', '_warnings', 'genericpath', 'stat', 'zipimport', '_sysconfigdata', 'warnings', 'UserDict', 'encodings.ascii', 'sys', 'codecs', '_sysconfigdata_nd', 'os.path', 'sitecustomize', 'signal', 'traceback', 'linecache', 'posix', 'encodings.aliases', 'exceptions', 'sre_parse', 'os', '_weakref']
*******************************************************************************
[<module &#39;copy_reg&#39; from &#39;/usr/lib/python2.7/copy_reg.pyc&#39;>, <module &#39;sre_compile&#39; from &#39;/usr/lib/python2.7/sre_compile.pyc&#39;>, <module &#39;_sre&#39; (built-in)>, <module &#39;encodings&#39; from &#39;/usr/lib/python2.7/encodings/__init__.pyc&#39;>, <module &#39;site&#39; from &#39;/usr/lib/python2.7/site.pyc&#39;>, <module &#39;__builtin__&#39; (built-in)>, <module &#39;sysconfig&#39; from &#39;/usr/lib/python2.7/sysconfig.pyc&#39;>, <module &#39;__main__&#39; from &#39;sys-test1.py&#39;>, None, <module &#39;abc&#39; from &#39;/usr/lib/python2.7/abc.pyc&#39;>, <module &#39;posixpath&#39; from &#39;/usr/lib/python2.7/posixpath.pyc&#39;>, <module &#39;_weakrefset&#39; from &#39;/usr/lib/python2.7/_weakrefset.pyc&#39;>, <module &#39;errno&#39; (built-in)>, None, <module &#39;sre_constants&#39; from &#39;/usr/lib/python2.7/sre_constants.pyc&#39;>, <module &#39;re&#39; from &#39;/usr/lib/python2.7/re.pyc&#39;>, <module &#39;_abcoll&#39; from &#39;/usr/lib/python2.7/_abcoll.pyc&#39;>, <module &#39;types&#39; from &#39;/usr/lib/python2.7/types.pyc&#39;>, <module &#39;_codecs&#39; (built-in)>, None, <module &#39;_warnings&#39; (built-in)>, <module &#39;genericpath&#39; from &#39;/usr/lib/python2.7/genericpath.pyc&#39;>, <module &#39;stat&#39; from &#39;/usr/lib/python2.7/stat.pyc&#39;>, <module &#39;zipimport&#39; (built-in)>, <module &#39;_sysconfigdata&#39; from &#39;/usr/lib/python2.7/_sysconfigdata.pyc&#39;>, <module &#39;warnings&#39; from &#39;/usr/lib/python2.7/warnings.pyc&#39;>, <module &#39;UserDict&#39; from &#39;/usr/lib/python2.7/UserDict.pyc&#39;>, <module &#39;encodings.ascii&#39; from &#39;/usr/lib/python2.7/encodings/ascii.pyc&#39;>, <module &#39;sys&#39; (built-in)>, <module &#39;codecs&#39; from &#39;/usr/lib/python2.7/codecs.pyc&#39;>, <module &#39;_sysconfigdata_nd&#39; from &#39;/usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc&#39;>, <module &#39;posixpath&#39; from &#39;/usr/lib/python2.7/posixpath.pyc&#39;>, <module &#39;sitecustomize&#39; from &#39;/usr/lib/python2.7/sitecustomize.pyc&#39;>, <module &#39;signal&#39; (built-in)>, <module &#39;traceback&#39; from &#39;/usr/lib/python2.7/traceback.pyc&#39;>, <module &#39;linecache&#39; from &#39;/usr/lib/python2.7/linecache.pyc&#39;>, <module &#39;posix&#39; (built-in)>, <module &#39;encodings.aliases&#39; from &#39;/usr/lib/python2.7/encodings/aliases.pyc&#39;>, <module &#39;exceptions&#39; (built-in)>, <module &#39;sre_parse&#39; from &#39;/usr/lib/python2.7/sre_parse.pyc&#39;>, <module &#39;os&#39; from &#39;/usr/lib/python2.7/os.pyc&#39;>, <module &#39;_weakref&#39; (built-in)>]
*******************************************************************************
<module &#39;os&#39; from &#39;/usr/lib/python2.7/os.pyc&#39;>
Copy after login

(4) sys.stdin/sys.stdout/sys.stderr

stdin, stdout, stderr are in All file attribute objects in Python are automatically related to the standard input, output, and errors in the shell environment when python is started. The I/O redirection of the python program in the shell is provided by the shell and has nothing to do with python itself. Relationship. The python program internally redirects stdin, stdout, and stderr read and write operations to an internal object.

Standard input

import sys
#print(&#39;Hi, %s!&#39; %input(&#39;Please enter your name: &#39;)) python3.*版本用input
print(&#39;Hi, %s!&#39; %raw_input(&#39;Please enter your name: &#39;)) #python2.*版本用raw_input
运行结果:
Please enter your name: er
Hi, er!
等同于:
 #!/usr/bin/python
import sys
print(&#39;Please enter your name:&#39;)
name=sys.stdin.readline()[:-1]
print(&#39;Hi, %s!&#39; %name)
标准输出
print(&#39;Hello World!\n&#39;)
等同于:
 #!/usr/bin/python
import sys
sys.stdout.write(&#39;output resule is good!\n&#39;)
其他实验
#!/usr/bin/python
import sys
for i in (sys.stdin, sys.stdout, sys.stderr):
    print(i)
Copy after login

Execution result:

python sys-test1.py
<open file &#39;<stdin>&#39;, mode &#39;r&#39; at 0x7fa4e630f0c0>
<open file &#39;<stdout>&#39;, mode &#39;w&#39; at 0x7fa4e630f150>
<open file &#39;<stderr>&#39;, mode &#39;w&#39; at 0x7fa4e630f1e0>
Copy after login

The above is the detailed content of Basic introduction to python sys module. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

How to access DeepSeekapi - DeepSeekapi access call tutorial How to access DeepSeekapi - DeepSeekapi access call tutorial Mar 12, 2025 pm 12:24 PM

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once

Major update of Pi Coin: Pi Bank is coming! Major update of Pi Coin: Pi Bank is coming! Mar 03, 2025 pm 06:18 PM

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

What are the current AI slicing tools? What are the current AI slicing tools? Nov 29, 2024 am 10:40 AM

Here are some popular AI slicing tools: TensorFlow DataSetPyTorch DataLoaderDaskCuPyscikit-imageOpenCVKeras ImageDataGenerator

See all articles