programing Python --Sys module

时间:2023-03-09 01:53:36
programing Python --Sys module

Recall that every python module has a built_in __name__ variable that python sets to the __main__ string only when the file is run as a program,not when it's imported as library

so in the python fiel if __name__ == "__main__" : .... is the top-level code

 '''
aplit and interactively page a string of file of text
''' def more(text,numlines= 15):
lines = str.splitlines(text)
while lines:
chunk = lines[:numlines]
lines = lines[numlines:]
for line in chunk:print(line)
if lines and raw_input('more?') not in ['y','Y']:break if __name__ == "__main__":
import sys
more(open(sys.argv[0]).read(),10)

when the more.py file is imported ,we pass an explicit string to its more function,so this is the imported way to run the more function

 from more import more
import sys
more(sys.__doc__)

Introducing the sys Module

   PlatForms and Versions

 if sys.platform[:3] == 'win':print ('hello windows')
elif sys.platform[:3] == 'lin':print ('hello linux')

If you have code that must act differently on different machines, simply test the sys.platform string as done,

The Module Search Path

sys.path is a list fo directory name strings representing the true search path in running python interpreter, when a module is imported python scans this list from left to right,searching for the module's file on each directory named in the list,

the sys.path list in simply initialized from your PYTHONPATH setting

Surprisingly,sys.path can actually be changed by program. using apend,extend,insert,pop,remove function

The Loaded Modules Table

sys.modules is a dictionary containing one name:module entry for every module imported in your python session

>>> sys.modules

Excepstion Detials

  other attribures in the sys module allow us to fetch all the information related to the most recently python exception,the sys.exc_info function returns a tuple with the latest exception's type,value and traceback object

 try:
raise IndexError
except:
print (sys.exc_info())

Other sys Module Exports:

  Command_line arguments show up as a list of string called sys.argv

  Standard streams are available as sys.stdin sys.stdout and sys.stderr

program exit can be forced with sys.exit calls