An introduction to sys modules in Python and how packages are imported and used

introduction to sys module in Python and usage of package import


1. Argv: implementation from the outside of the program to the program to pass the parameter
in F:\Pywork temp.py file to write the following code :

import sys
print (sys.argv[0])#文件名
print (sys.argv[1])#传入的外部参数
命令行:
F:\Pywork> python temp.py "andy"
temp.py
andy

2. sys. Modules. Keys () returns all have imported module list
3. sys. Exit (n)

function: at the end of the main program, the interpreter exits automatically, but if you need to exit the program, you can call sys.exit with an optional integer argument returned to the calling program, indicating that you can capture a call to sys.exit from the main program. (0 is normal exit, others are exceptions)

4.sys.path

function: get the string collection of specified module search path, you can put the written module under the path, you can find

correctly when import in the program

sys.path.append("自定义模块路径")

5. Sys. Returns the imported module field system modules, the key is the module name, the value is the module
6. Sys. Stdin, sys. Stdout, sys. Stderr: stdin, stdout, and stderr variable contains corresponding with the standard I/O flow stream objects. If you need more control over the output, and print doesn't give you what you want, that's all you need. You can also replace them by redirecting output and input to other devices, or processing them in a nonstandard way.

import sys 
sys.stdout.write('HelloWorld!')
print ('Please enter yourname:')
name=sys.stdin.readline()[:-1]
print 'Hi, %s!' % name

Package import in python and use
first, there are three ways to import a package. Take importing sys package as an example

import sys 
print("-----------python modules-----------")
print("命令行参数:")
for x in sys.argv:  #sys.argv传递给Python脚本的命令行参数列表。argv[0]是脚本名
    #argv[1]就是执行脚本命令行外部传递的第一个参数,[2]就是第二个
    print(x)
print("Python的路径是:",sys.path)

is the normal import method, and the sys package is imported using the sys. function name to use the sys built-in function

from sys import argv,path
print("-----------python modules-----------")
print("命令行参数:")
for x in argv:  
    print(x)
print("Python的路径是:",path)

is a built-in function specified by sys, which can be used directly. Sys.

is not required

import sys as s
print("-----------python modules-----------")
print("命令行参数:")
for x in s.argv:  
    print(x)
print("Python的路径是:",s.path)

USES as to rename sys packages for later use.


Read More: