python——sys模块

sys.argv

功能:在外部向程序内部传递参数
示例:sys.py

import sys
print sys.argv[0]
print sys.argv[1]

运行:

>>>python sys.py argv1
sys.py
argv1

sys.exit(n)

功能:执行到主程序末尾,解释器自动退出,但是如果需要中途退出程序,可以调用sys.exit函数,带有一个可选的整数参数返回给调用它的程序,表示你可以在主程序中捕获对sys.exit的调用。(0是正常退出,其他为异常)

示例:exit.py

#!/usr/bin/env python
import sys

def exitfunc(value):
    print value
    sys.exit(0)

print "hello"
try:
    sys.exit(1)
except SystemExit,value:
    exitfunc(value)
print "come?"

运行:

>>> python exit.py
hello
1

sys.exitfunc (回调函数)

通过sys.exitfunc来注册程序退出时的回调函数,我们可以在这个回调函数中做一些资源清理的操作,
但通过它只能注册一个回调,而且还不支持参数(可以带默认参数)。
【1】exit_handler.py文件:

#!usr/bin/env python
#coding:utf-8
import sys
def exitfunc():
    print 'exit is done!'
sys.exitfunc=exitfunc #注册回调函数
if __name__=='__main__':
    print 'hello world'
  #程序运行结束,在退出解释器之前,会自动调用回调函数。。
>>> python exit_handler.py
hello world
exit is done!

【2】exit_handler1.py文件:

#!usr/bin/env python  
#coding:utf-8  
import sys  
def exitfunc():  
    print 'exit is done!'  
sys.exitfunc=exitfunc  #通过sys.exitfunc来注册程序退出时的回调函数  
print 'hello world'  
sys.exit(1)#执行至主程序的末尾时,解释器会自动退出。 我们也可以调用sys.exit函数使程序中途退出解释器!  
print 'ok'#该语句不执行
>>> python exit_handler1.py
hello world
exit is done!

【3】exit_handler2.py文件:

#!usr/bin/env python
#coding:utf-8
import sys
def exitfunc():
    print 'exit is done!'
sys.exitfunc=exitfunc
if __name__=='__main__':
    import os
    print '回调函数没有执行!'
    os._exit(0) #通过os._exit()退出,注册的回调函数将不会被调用
>>> python exit_handler3.py
回调函数没有执行!

通过os._exit()退出,注册的回调函数将不会被调用

关于回调函数,sys.exitfunc有其自身的缺点,比如,只能注册一个回调函数,不能传递参数。。。为了更加方便的注册回调,我们一般使用atexit模块。。。

关于atexit模块,请参考:点击打开链接

sys.path

本着下定义开头吧:python中import某个A模块时,首先会从python的内置模块中查找是否含义该模块的定义若未查询到会从sys.path对应的模块路径查询是否含有对应模块的定义,如果搜索完成依然没有对应A模块时则抛出import的异常

接着说明下python的两种加载py文件的方式:

  • python xxx.py
  • python -m xxx.py

第一种方式是直接运行方式

第二种方式是把模块当做脚本来启动

可能看起来说的python运行方式和sys.path有点大相径庭,但实际上两种不同方式的运行导致sys.path[0]的值是有差异的

第一种方式:sys.path[0]是当前脚本的运行目录

第二种方式:sys.path[0]是空值字符串,也就是当前执行python的目录

sys.path是一个python搜索模块的路径列表:
 eg、下边的X.py文件中打印出sys.path内容:

import sys
print sys.path

python X.py运行

其中sys.path[0]是 I:\restful_code\tester,对应调用python解释器的脚本所在的目录。 其实就是存放需要运行的代码的路径

python -m x.py运行

 使用场景:

 在实际开发中,默认包含了当前目录为搜索路径,所以,当前目录下的模块和子模块均可以正常访问。但是若一个模块需要import平级的不同目录的模块,或者上级目录里面的模块,就可以通过修改path来实现

 修改path的两种方法:

方法一:函数添加
这是即时生效的方法,就是在模块里面修改sys.path值,这种方法修改的sys.path作用域只是当前进程,进程结束后就失效了。
个人比较推荐这种方法,比较干净, 避免一些冲突问题。
比如现在的代码目录结构:
/src/configs/config.py
/src/common/Database.py
假如Database.py期望导入config. py,则可以增加上级目录到sys.path列表里面:

parent_path = os.path.dirname(sys.path[0]) 
if parent_path not in sys.path: 
    sys.path.append(parent_path) 
import configs.config

方法一:修改环境变量

添加系统环境变量PYTHONPATH,在这个环境变量中输入相关的路径,不同的路径之间用逗号(英文的!)分开。路径会自动加入到sys.path中。

os.path.abspath(__file__) 作用: 获取当前脚本的完整路径
sys.path.append(’引用模块的地址')对于模块和自己写的程序不在同一个目录下,
可以把模块的路径通过sys.path.append(路径)添加到程序中。 

sys.modules

sys.modules是一个全局字典,该字典是python启动后就加载在内存中。每当程序员导入新的模块,sys.modules都将记录这些模块。字典sys.modules对于加载模块起到了缓冲的作用。当某个模块第一次导入,字典sys.modules将自动记录该模块。当第二次再导入该模块时,python会直接到字典中查找,从而加快了程序运行的速度。

字典sys.modules具有字典所拥有的一切方法,可以通过这些方法了解当前的环境加载了哪些模块

import os
import shutil
import sys
print sys.modules
{'code': <module 'code' from 'D:\ana\envs\py27\lib\code.pyc'>, 'numpy.core.info': <module 'numpy.core.info' from 'D:\ana\envs\py27\lib\site-packages\numpy\core\info.pyc'>, '_pydevd_bundle.code': None, 'ctypes.os': None, 'gc': <module 'gc' (built-in)>, '_pydevd_bundle.os': None, 'distutils.sysconfig': <module 'distutils.sysconfig' from 'D:\ana\envs\py27\lib\distutils\sysconfig.pyc'>, 'pkg_resources._vendor.traceback': None, 'email.warnings': None, 'pkg_resources._vendor.packaging.__about__': <module 'pkg_resources._vendor.packaging.__about__' from 'D:\ana\envs\py27\lib\site-packages\pkg_resources\_vendor\packaging\__about__.pyc'>, '_pydev_bundle._pydev_completer': <module '_pydev_bundle._pydev_completer' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_bundle\_pydev_completer.py'>, 'pprint': <module 'pprint' from 'D:\ana\envs\py27\lib\pprint.pyc'>, 'pydevd_concurrency_analyser.pydevd_concurrency_logger': <module 'pydevd_concurrency_analyser.pydevd_concurrency_logger' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\pydevd_concurrency_analyser\pydevd_concurrency_logger.py'>, 'unittest.sys': None, 'numpy.core.umath': <module 'numpy.core.umath' from 'D:\ana\envs\py27\lib\site-packages\numpy\core\umath.pyc'>, 'numpy._pytesttester': <module 'numpy._pytesttester' from 'D:\ana\envs\py27\lib\site-packages\numpy\_pytesttester.pyc'>, 'string': <module 'string' from 'D:\ana\envs\py27\lib\string.pyc'>, 'SocketServer': <module 'SocketServer' from 'D:\ana\envs\py27\lib\SocketServer.pyc'>, 'numpy.lib.arraysetops': <module 'numpy.lib.arraysetops' from 'D:\ana\envs\py27\lib\site-packages\numpy\lib\arraysetops.pyc'>, 'pydevd_concurrency_analyser.time': None, 'numpy.core._multiarray_tests': <module 'numpy.core._multiarray_tests' from 'D:\ana\envs\py27\lib\site-packages\numpy\core\_multiarray_tests.pyd'>, '_pydevd_bundle.pydevd_comm_constants': <module '_pydevd_bundle.pydevd_comm_constants' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_comm_constants.py'>, 'email.quoprimime': <module 'email.quoprimime' from 'D:\ana\envs\py27\lib\email\quoprimime.pyc'>, 'json.encoder': <module 'json.encoder' from 'D:\ana\envs\py27\lib\json\encoder.pyc'>, 'subprocess': <module 'subprocess' from 'D:\ana\envs\py27\lib\subprocess.pyc'>, 'numpy.core.machar': <module 'numpy.core.machar' from 'D:\ana\envs\py27\lib\site-packages\numpy\core\machar.pyc'>, '_pydevd_bundle.pydevd_dont_trace_files': <module '_pydevd_bundle.pydevd_dont_trace_files' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_dont_trace_files.py'>, 'unittest.StringIO': None, 'encodings._codecs_cn': None, 'email.codecs': None, 'numpy.ma.extras': <module 'numpy.ma.extras' from 'D:\ana\envs\py27\lib\site-packages\numpy\ma\extras.pyc'>, 'numpy.fft.fftpack_lite': <module 'numpy.fft.fftpack_lite' from 'D:\ana\envs\py27\lib\site-packages\numpy\fft\fftpack_lite.pyd'>, 'math': <module 'math' (built-in)>, 'dis': <module 'dis' from 'D:\ana\envs\py27\lib\dis.pyc'>, 'zlib': <module 'zlib' (built-in)>, '_pydevd_bundle.pydevd_cython_wrapper': <module '_pydevd_bundle.pydevd_cython_wrapper' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_cython_wrapper.py'>, 'pkg_resources._vendor.pprint': None, '_pydevd_bundle.pydevd_extension_api': <module '_pydevd_bundle.pydevd_extension_api' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_extension_api.py'>, '_pydev_bundle.pydev_log': <module '_pydev_bundle.pydev_log' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_bundle\pydev_log.py'>, 'numpy.core._ctypes': None, 'matplotlib.cbook.warnings': None, 'unittest.pprint': None, 'encodings.gbk': <module 'encodings.gbk' from 'D:\ana\envs\py27\lib\encodings\gbk.pyc'>, 'matplotlib.cbook.textwrap': None, 'abc': <module 'abc' from 'D:\ana\envs\py27\lib\abc.pyc'>, '_warnings': <module '_warnings' (built-in)>, 'pkg_resources._vendor.collections': None, 'numpy._globals': <module 'numpy._globals' from 'D:\ana\envs\py27\lib\site-packages\numpy\_globals.pyc'>, 'numpy.lib.npyio': <module 'numpy.lib.npyio' from 'D:\ana\envs\py27\lib\site-packages\numpy\lib\npyio.pyc'>, 'pkg_resources._vendor.copy': None, 'matplotlib.sys': None, 'ntpath': <module 'ntpath' from 'D:\ana\envs\py27\lib\ntpath.pyc'>, 'numpy.fft.helper': <module 'numpy.fft.helper' from 'D:\ana\envs\py27\lib\site-packages\numpy\fft\helper.pyc'>, 'pydev_ipython': <module 'pydev_ipython' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\pydev_ipython\__init__.py'>, 'unittest.suite': <module 'unittest.suite' from 'D:\ana\envs\py27\lib\unittest\suite.pyc'>, '_pydevd_bundle._pydev_imps': None, 'matplotlib': <module 'matplotlib' from 'D:\ana\envs\py27\lib\site-packages\matplotlib\__init__.pyc'>, 'exceptions': <module 'exceptions' (built-in)>, 'json.scanner': <module 'json.scanner' from 'D:\ana\envs\py27\lib\json\scanner.pyc'>, 'codecs': <module 'codecs' from 'D:\ana\envs\py27\lib\codecs.pyc'>, 'numpy.os': None, '_pydevd_bundle.types': None, 'email.socket': None, 'StringIO': <module 'StringIO' from 'D:\ana\envs\py27\lib\StringIO.pyc'>, 'pkg_resources': <module 'pkg_resources' from 'D:\ana\envs\py27\lib\site-packages\pkg_resources\__init__.pyc'>, 'weakref': <module 'weakref' from 'D:\ana\envs\py27\lib\weakref.pyc'>, 'numpy.core._internal': <module 'numpy.core._internal' from 'D:\ana\envs\py27\lib\site-packages\numpy\core\_internal.pyc'>, '_pydevd_bundle': <module '_pydevd_bundle' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\__init__.py'>, 'distutils.sys': None, 'numpy.lib.arraypad': <module 'numpy.lib.arraypad' from 'D:\ana\envs\py27\lib\site-packages\numpy\lib\arraypad.pyc'>, '_pydevd_bundle.abc': None, '_pydevd_bundle.pydevd_plugin_utils': <module '_pydevd_bundle.pydevd_plugin_utils' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydevd_bundle\pydevd_plugin_utils.py'>, 'base64': <module 'base64' from 'D:\ana\envs\py27\lib\base64.pyc'>, '_pydevd_bundle.linecache': None, '_json': <module '_json' (built-in)>, 'email.FeedParser': <email.LazyImporter object at 0x00000000134E9748>, 'pkg_resources._vendor.warnings': None, 'email.charset': <module 'email.charset' from 'D:\ana\envs\py27\lib\email\charset.pyc'>, 'pkg_resources._vendor.datetime': None, '_pydev_imps': <module '_pydev_imps' from 'D:\pycharm\PyCharm 2020.1\plugins\python\helpers\pydev\_pydev_imps\__init__.py'>, 'select': <module 'select' from 'D:\ana\envs\py27\DLLs\select.pyd'>, 'ctypes._ctypes': None, '_heapq': <module '_heapq' (built-in)>, 'six.moves.urllib': <module 'six.moves.urllib' (built-in)>, '_pydev_bundle._subprocess': None, 'numpy.lib.financial': <module 'numpy.lib.financial' from 'D:\ana\envs\py27\lib\site-packages\numpy\lib\financial.pyc'>, 'pkg_resources._vendor.packaging.specifiers': <module 'pkg_resources._vendor.packaging.specifiers' from 'D:\ana\envs\py27\lib\site-packages\pkg_resources\_vendor\packaging\specifiers.pyc'>, 'binascii': <module 'binascii' (built-in)>, 'email.MIMEMessage': <email.LazyImporter object at 0x00000000134E7088>, 'email._parseaddr': <module 'email._parseaddr' from 'D:\ana\envs\py27\lib\email\_parseaddr.pyc'>, 'email.sys': None, 'tokenize': <module 'tokenize' from 'D:\ana\envs\py27\lib\tokenize.pyc'>, 'numpy.core.numpy': None, 'numpy.polynomial.chebyshev': <module 'numpy.polynomial.chebyshev' from 'D:\ana\envs\py27\lib\site-packages\numpy\polynomial\chebyshev.pyc'>, 'pkg_resources.extern.six.moves.ur
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python标准库中的sys模块是一个提供了与Python解释器和运行时环境交互的功能的模块sys模块提供了许多与系统相关的功能和变量。其中一些常用的功能包括: 1. version:sys.version变量可以用来获取当前Python解释器的版本信息。它返回一个字符串,包含Python的版本号和一些其他的信息。 2. version_info:sys.version_info变量可以用来获取当前Python解释器的详细版本信息。它返回一个命名元组,包含主版本号、次版本号、修订版本号和其他一些信息。 3. executable:sys.executable变量可以用来获取当前Python解释器的可执行文件路径。它返回一个字符串,表示Python解释器的路径。 使用sys模块可以方便地获取Python解释器的版本信息以及其他与系统相关的信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Python标准库学习——sys模块](https://blog.csdn.net/weixin_51995147/article/details/124616458)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Python常用标准库-sys库一文详解](https://blog.csdn.net/master_hunter/article/details/129257178)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值