Python基础之sys模块

sys模块是与python解释器交互的一个接口,是Python自带的模块。当执行import sys后,在sys.path变量中所列目录中查找sys模块文件,然后运行这个模块的主块中的语句进行初始化,然后就可以使用模块了。我们可以通过dir()函数来查看每个模块中可用的方法:

import sys

print(dir(sys))

结果:

['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__', '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_debugmallocstats', '_enablelegacywindowsfsencoding', '_framework', '_getframe', '_git', '_home', '_xoptions', 'api_version', 'argv', 'base_exec_prefix', 'base_prefix', 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth', 'get_coroutine_wrapper', 'getallocatedblocks', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval', 'gettrace', 'getwindowsversion', 'hash_info', 'hexversion', 'implementation', 'int_info', 'intern', 'is_finalizing', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'set_coroutine_wrapper', 'setcheckinterval', 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout', 'thread_info', 'version', 'version_info', 'warnoptions', 'winver']

Process finished with exit code 0

我么可以看到,sys模块中的方法非常的多,下面我们仅仅演示一些常用的模块方法。

sys.argv 

实现从程序外部向程序传递参数。
sys.argv 变量是一个包含了命令行参数的字符串列表, 利用命令行想程序传递参数. 其中,脚本的名称总是 sys.argv 列表的第一个参数。

(2) sys.path 

包含输入模块的目录名列表。
获取指定模块搜索路径的字符串集合,可以将写好的模块放在得到的某个路径下,就可以在程序中import时正确找到。在import导入module_name时,就是根据sys.path的路径来搜索module.name,也可以自定义添加模块路径。 
sys.path.append(“自定义模块路径”)。

import sys

print("can you hear me?")
for i in sys.argv:
    print(i)

print("\n\nPython路径是:", sys.path, "\n")

结果:

can you hear me?
D:/Python/Day25/Test.py


Python路径是: ['D:\\Python\\Day25', 'D:\\Python\\Day25', 'D:\\Python\\Day25\\venv\\Scripts\\python37.zip', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37', 'D:\\Python\\Day25\\venv', 'D:\\Python\\Day25\\venv\\lib\\site-packages', 'D:\\Python\\Day25\\venv\\lib\\site-packages\\setuptools-39.1.0-py3.7.egg', 'D:\\Python\\Day25\\venv\\lib\\site-packages\\pip-10.0.1-py3.7.egg', 'C:\\Program Files\\JetBrains\\PyCharm 2018.2\\helpers\\pycharm_matplotlib_backend'] 


Process finished with exit code 0

sys.modules 
sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法.

import sys


def exitfunc(value):
    print(value)
    sys.exit(0)  # 正常退出


print('--------------')

try:
    sys.exit(1)
except SystemExit as value:
    exitfunc(value)

print("test")  # 程序结束,不能走到这里

结果:

--------------
1

Process finished with exit code 0

sys.modules

sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。它拥有字典所拥有的一切方法。

import sys

print(sys.modules.keys())
print("-----------LINE--------------")
print(sys.modules.values())
print("-----------LINE--------------")
print(sys.modules['os'])

结果:

dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_thread', '_warnings', '_weakref', 'zipimport', '_frozen_importlib_external', '_io', 'marshal', 'nt', 'winreg', 'encodings', 'codecs', '_codecs', 'encodings.aliases', 'encodings.utf_8', '_signal', '__main__', 'encodings.latin_1', 'io', 'abc', '_abc', 'site', 'os', 'stat', '_stat', 'ntpath', 'genericpath', 'os.path', '_collections_abc', '_sitebuiltins', '_bootlocale', '_locale', 'encodings.gbk', '_codecs_cn', '_multibytecodec', 'encodings.cp437', 'sitecustomize'])
-----------LINE--------------
dict_values([<module 'sys' (built-in)>, <module 'builtins' (built-in)>, <module '_frozen_importlib' (frozen)>, <module '_imp' (built-in)>, <module '_thread' (built-in)>, <module '_warnings' (built-in)>, <module '_weakref' (built-in)>, <module 'zipimport' (built-in)>, <module '_frozen_importlib_external' (frozen)>, <module 'io' (built-in)>, <module 'marshal' (built-in)>, <module 'nt' (built-in)>, <module 'winreg' (built-in)>, <module 'encodings' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\__init__.py'>, <module 'codecs' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\codecs.py'>, <module '_codecs' (built-in)>, <module 'encodings.aliases' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\aliases.py'>, <module 'encodings.utf_8' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\utf_8.py'>, <module '_signal' (built-in)>, <module '__main__' from 'D:/Python/Day25/Test.py'>, <module 'encodings.latin_1' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\latin_1.py'>, <module 'io' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\io.py'>, <module 'abc' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\abc.py'>, <module '_abc' (built-in)>, <module 'site' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site.py'>, <module 'os' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>, <module 'stat' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\stat.py'>, <module '_stat' (built-in)>, <module 'ntpath' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\ntpath.py'>, <module 'genericpath' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\genericpath.py'>, <module 'ntpath' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\ntpath.py'>, <module '_collections_abc' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\_collections_abc.py'>, <module '_sitebuiltins' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\_sitebuiltins.py'>, <module '_bootlocale' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\_bootlocale.py'>, <module '_locale' (built-in)>, <module 'encodings.gbk' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\gbk.py'>, <module '_codecs_cn' (built-in)>, <module '_multibytecodec' (built-in)>, <module 'encodings.cp437' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\encodings\\cp437.py'>, <module 'sitecustomize' from 'C:\\Program Files\\JetBrains\\PyCharm 2018.2\\helpers\\pycharm_matplotlib_backend\\sitecustomize.py'>])
-----------LINE--------------
<module 'os' from 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python37\\lib\\os.py'>

Process finished with exit code 0

sys.stdin/sys.stdout/sys.stderr 
stdin、stdout和stderr在Python中都是文件属性对象,他们在python启动时自动与shell环境中的标准输入,输出,出错相关。而python程序在shell中的I/O重定向是有shell来提供的,与python本身没有关系,python程序内部将stdin,stdout,stderr读写操作重定向到一个内部对象。

sys.stdin

import sys

print("Hello,%s" % input("请输入你的名字:"))
print("-----------LINE--------------")
print("请输入你的名字:")
name = sys.stdin.readline()[:-1]
print("Hello,%s" % name)

结果:

请输入你的名字:张三
Hello,张三
-----------LINE--------------
请输入你的名字:
张三
Hello,张三

Process finished with exit code 0

sys.stdout

import sys

print("这是标准输出!")
sys.stdout.write("这是使用sys输出")

结果:

这是标准输出!
这是使用sys输出
Process finished with exit code 0

请注意sys.stdout输出结束没有换行,也不能使用end = '\n'来强制换行。

sys.stderr

import sys

for i in (sys.stdin, sys.stdout, sys.stderr):
    print(i)

结果:

<_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_33567641/article/details/81388293