Basic introduction to python sys module
1: sys is a built-in module of python.
Use the import statement to enter the sys module.
Related recommendations: "python Video"
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']
(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'
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']
(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?")
Running results:
hello 90
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"])
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 'copy_reg' from '/usr/lib/python2.7/copy_reg.pyc'>, <module 'sre_compile' from '/usr/lib/python2.7/sre_compile.pyc'>, <module '_sre' (built-in)>, <module 'encodings' from '/usr/lib/python2.7/encodings/__init__.pyc'>, <module 'site' from '/usr/lib/python2.7/site.pyc'>, <module '__builtin__' (built-in)>, <module 'sysconfig' from '/usr/lib/python2.7/sysconfig.pyc'>, <module '__main__' from 'sys-test1.py'>, None, <module 'abc' from '/usr/lib/python2.7/abc.pyc'>, <module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>, <module '_weakrefset' from '/usr/lib/python2.7/_weakrefset.pyc'>, <module 'errno' (built-in)>, None, <module 'sre_constants' from '/usr/lib/python2.7/sre_constants.pyc'>, <module 're' from '/usr/lib/python2.7/re.pyc'>, <module '_abcoll' from '/usr/lib/python2.7/_abcoll.pyc'>, <module 'types' from '/usr/lib/python2.7/types.pyc'>, <module '_codecs' (built-in)>, None, <module '_warnings' (built-in)>, <module 'genericpath' from '/usr/lib/python2.7/genericpath.pyc'>, <module 'stat' from '/usr/lib/python2.7/stat.pyc'>, <module 'zipimport' (built-in)>, <module '_sysconfigdata' from '/usr/lib/python2.7/_sysconfigdata.pyc'>, <module 'warnings' from '/usr/lib/python2.7/warnings.pyc'>, <module 'UserDict' from '/usr/lib/python2.7/UserDict.pyc'>, <module 'encodings.ascii' from '/usr/lib/python2.7/encodings/ascii.pyc'>, <module 'sys' (built-in)>, <module 'codecs' from '/usr/lib/python2.7/codecs.pyc'>, <module '_sysconfigdata_nd' from '/usr/lib/python2.7/plat-x86_64-linux-gnu/_sysconfigdata_nd.pyc'>, <module 'posixpath' from '/usr/lib/python2.7/posixpath.pyc'>, <module 'sitecustomize' from '/usr/lib/python2.7/sitecustomize.pyc'>, <module 'signal' (built-in)>, <module 'traceback' from '/usr/lib/python2.7/traceback.pyc'>, <module 'linecache' from '/usr/lib/python2.7/linecache.pyc'>, <module 'posix' (built-in)>, <module 'encodings.aliases' from '/usr/lib/python2.7/encodings/aliases.pyc'>, <module 'exceptions' (built-in)>, <module 'sre_parse' from '/usr/lib/python2.7/sre_parse.pyc'>, <module 'os' from '/usr/lib/python2.7/os.pyc'>, <module '_weakref' (built-in)>] ******************************************************************************* <module 'os' from '/usr/lib/python2.7/os.pyc'>
(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('Hi, %s!' %input('Please enter your name: ')) python3.*版本用input print('Hi, %s!' %raw_input('Please enter your name: ')) #python2.*版本用raw_input 运行结果: Please enter your name: er Hi, er! 等同于: #!/usr/bin/python import sys print('Please enter your name:') name=sys.stdin.readline()[:-1] print('Hi, %s!' %name) 标准输出 print('Hello World!\n') 等同于: #!/usr/bin/python import sys sys.stdout.write('output resule is good!\n') 其他实验 #!/usr/bin/python import sys for i in (sys.stdin, sys.stdout, sys.stderr): print(i)
Execution result:
python sys-test1.py <open file '<stdin>', mode 'r' at 0x7fa4e630f0c0> <open file '<stdout>', mode 'w' at 0x7fa4e630f150> <open file '<stderr>', mode 'w' at 0x7fa4e630f1e0>
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
