python系统编程第1节

python系统编程第1节

1、#使用print命令查看帮助文档

>>> print(sys.__doc__)

This module provides access to some objects used or maintained by the

interpreter and to functions that interact strongly with the interpreter.


Dynamic objects:


argv -- command line arguments; argv[0] is the script pathname if known

path -- module search path; path[0] is the script directory, else ''

modules -- dictionary of loaded modules


displayhook -- called to show results in an interactive session

excepthook -- called to handle any uncaught exception other than SystemExit

  To customize printing in an interactive session or to install a custom

  top-level exception handler, assign other functions to replace these.


stdin -- standard input file object; used by input()

stdout -- standard output file object; used by print()

stderr -- standard error object; used for error messages

  By assigning other file objects (or objects that behave like files)

  to these, it is possible to redirect all of the interpreter's I/O.


last_type -- type of last uncaught exception

last_value -- value of last uncaught exception

last_traceback -- traceback of last uncaught exception

  These three are only available in an interactive session after a

  traceback has been printed.


Static objects:


builtin_module_names -- tuple of module names built into this interpreter

copyright -- copyright notice pertaining to this interpreter

exec_prefix -- prefix used to find the machine-specific Python library

executable -- absolute path of the executable binary of the Python interpreter

float_info -- a struct sequence with information about the float implementation.

float_repr_style -- string indicating the style of repr() output for floats

hash_info -- a struct sequence with information about the hash algorithm.

hexversion -- version information encoded as a single integer

implementation -- Python implementation information.

int_info -- a struct sequence with information about the int implementation.

maxsize -- the largest supported length of containers.

maxunicode -- the value of the largest Unicode code point

platform -- platform identifier

prefix -- prefix used to find the Python library

thread_info -- a struct sequence with information about the thread implementation.

version -- the version of this interpreter as a string

version_info -- version information as a named tuple

__stdin__ -- the original stdin; don't touch!

__stdout__ -- the original stdout; don't touch!

__stderr__ -- the original stderr; don't touch!

__displayhook__ -- the original displayhook; don't touch!

__excepthook__ -- the original excepthook; don't touch!


Functions:


displayhook() -- print an object to the screen, and save it in builtins._

excepthook() -- print an exception and its traceback to sys.stderr

exc_info() -- return thread-safe information about the current exception

exit() -- exit the interpreter by raising SystemExit

getdlopenflags() -- returns flags to be used for dlopen() calls

getprofile() -- get the global profiling function

getrefcount() -- return the reference count for an object (plus one :-)

getrecursionlimit() -- return the max recursion depth for the interpreter

getsizeof() -- return the size of an object in bytes

gettrace() -- get the global debug tracing function

setcheckinterval() -- control how often the interpreter checks for events

setdlopenflags() -- set the flags to be used for dlopen() calls

setprofile() -- set the global profiling function

setrecursionlimit() -- set the max recursion depth for the interpreter

settrace() -- set the global debug tracing function



2、#使用help命令查看帮助文档

>>> help(sys)

Help on built-in module sys:


NAME

    sys


MODULE REFERENCE

    https://docs.python.org/3.5/library/sys.html

    

    The following documentation is automatically generated from the Python

    source files.  It may be incomplete, incorrect or include features that

    are considered implementation detail and may vary between Python

    implementations.  When in doubt, consult the module reference at the

    location listed above.


DESCRIPTION

    This module provides access to some objects used or maintained by the

    interpreter and to functions that interact strongly with the interpreter.

    

    Dynamic objects:

    

    argv -- command line arguments; argv[0] is the script pathname if known

    path -- module search path; path[0] is the script directory, else ''

    modules -- dictionary of loaded modules

    

    displayhook -- called to show results in an interactive session

    excepthook -- called to handle any uncaught exception other than SystemExit

      To customize printing in an interactive session or to install a custom

      top-level exception handler, assign other functions to replace these.

    

    stdin -- standard input file object; used by input()

    stdout -- standard output file object; used by print()

    stderr -- standard error object; used for error messages

      By assigning other file objects (or objects that behave like files)

      to these, it is possible to redirect all of the interpreter's I/O.


3、#split和splitlines区别


Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 02:23:56) [MSC v.1913 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.                                                       

>>> line='aaa\nbbb\nccc\n'                                                                        

>>> line                                                                                                                     

'aaa\nbbb\nccc\n'                                                                                 

>>> line.split('\n')                                                  

['aaa', 'bbb', 'ccc', '']                                                                                                    

>>> line.splitlines()         #splitlines 相当于splint('\n')                                                                                                

['aaa', 'bbb', 'ccc']  


4、#字符串查找与替换(find和replace)

>>> mystr ='xxxSPAMxxx'

>>> mystr.find('SPAM')

3

>>> mystr = 'xxxaaxxaa'

>>> mystr.replace('aa','SPAM')

'xxxSPAMxxSPAM'


5、#in (判断运算符)、find(查找字符串)、strip和rstrip(去除字符串结尾的空格)


>>> mystr = 'xxxSPAMxxx'

>>> 'SPAM' in mystr

True

>>> 'Ni' in mystr

False

>>> mystr.find('Ni')

-1

>>> mystr = '\t Ni\n'

>>> mystr.strip()

'Ni'

>>> mystr.rstrip()

'\t Ni'


6、# lower(大写转小写)、isalpha和isdigit(测试内容)、string(字符串模块的空白分隔符)

>>> mystr='SHRUBBERY'

>>> mystr.lower()

'shrubbery'

>>> mystr.isalpha()

True

>>> mystr.isdigit()

False

>>> import string

>>> string.ascii_lowercase

'abcdefghijklmnopqrstuvwxyz'

>>> string.whitespace

' \t\n\r\x0b\x0c'


7、#分割字符串函数split、使用join将字符串连接、list转换成字符组成的列表


>>> mystr = 'aaa,bbb,ccc'                                             

>>> mystr.split(',')                                                                                                         

['aaa', 'bbb', 'ccc']                                                                             

>>> mystr = 'a b\nc\nd'                                               

>>> mystr                                                                                         

'a b\nc\nd'                                                                                       

>>> mystr.split()                                                                                 

['a', 'b', 'c', 'd']                                                                              

>>> delim = 'NI'                                                                                  

>>> delim.join(['aaa','bbb','ccc'])                                                                                          

'aaaNIbbbNIccc'                                                                                   

>>> ' '.join(['A','dead','parrot'])                                                                                          

'A dead parrot'                                                                                   

>>> chars =list('Lorreta')                                                                                                   

>>> chars                                                                                         

['L', 'o', 'r', 'r', 'e', 't', 'a']                                   

>>> chars.append('!')                                                                                                        

>>> ''.join(chars)                                                                                                           

'Lorreta!'      


8、#使用split和join来实现前面的replace

>>> mystr = 'xxaaxxaa'

>>> 'SPAM'.join(mystr.split('aa'))

'xxSPAMxxSPAM'


9、#字符串转整数、整数转字符串、字符串和整数加数

>>> int("42"),eval("42")

(42, 42)

>>> str(42),repr(42)

('42', '42')

>>> ("%d" % 42), '{:d}'.format(42)

('42', '42')

>>> "42" + str(1),int("42") + 1

('421', 43)


10、#open函数用法

>>> file = open('spam.txt','w')        #创建一个文件名叫:spam.txt

>>> file.write(('spam' * 5) + '\n')    #在文件中写入数据spam * 5次

21

>>> file.close()                                 #关闭文件推出

>>> file = open('spam.txt')             #打开文件spam.txt

>>> text = file.read()                       #设置变量将变量传入读文件

>>> text                                            #输出传入的数据

'spamspamspamspamspam\n'

    

11、# more.py分页脚本,需要放入system下执行。

c:\Windows\system>python more.py more.py                                 

#!/usr/bin/env python                                                                             

"""                                                

more is file                                                             

"""                                                               


def more(text,numlines=15):                                                                       

        lines = text.splitlines()       #split('\n'),this is not''            

        while lines:                                                            

                chunk = lines[:numlines]

                lines = lines[numlines:]                                 

More?y                                                                   

                for line in chunk:                                     

                        print(line)                                         

                if lines and input('More?') not in ['y','Y']:            

                        break


if __name__ == '__main__':                                                                        

        import sys                                                                

        more(open(sys.argv[1]).read(),10)


12、#使用more.py脚本进行导入并输出sys.__doc__ 输出分页信息


c:\Windows\system>python

Python 3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 02:23:56) [MSC v.1913 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> from more import more                                                

>>> import sys                                                    

>>> more(sys.__doc__)                   

This module provides access to some objects used or maintained by the                             

interpreter and to functions that interact strongly with the interpreter.     


Dynamic objects:                                             


argv -- command line arguments; argv[0] is the script pathname if known

path -- module search path; path[0] is the script directory, else ''

modules -- dictionary of loaded modules


displayhook -- called to show results in an interactive session

excepthook -- called to handle any uncaught exception other than SystemExit

  To customize printing in an interactive session or to install a custom                          

  top-level exception handler, assign other functions to replace these.                           


stdin -- standard input file object; used by input()                  

More?y                                             


13、#如果使用more(sys.__doc__,5) 的话每次显示5行信息


14、#查看python解释器的版本号

>>> import sys                                                           

>>> sys.platform,sys.maxsize,sys.version                                 

('win32', 2147483647, '3.6.5rc1 (v3.6.5rc1:f03c5148cf, Mar 14 2018, 02:23:56) [MSC v.1913 32 bit (Intel)]')

             

>>> if sys.platform[:3] == 'win':                                                                 

...     print('hello windows')                      

...                                                                                                        

hello windows     


15、#sys.path模块使用

在windows中显示如下:

>>> sys.path                                        

['', 'C:\\Program Files\\Python36-32\\python36.zip', 'C:\\Program Files\\Python36-32\\DLLs', 'C:\\Program Files\\Python36-32\

\lib', 'C:\\Program Files\\Python36-32', 'C:\\Program Files\\Python36-32\\lib\\site-packages']  


在linux中显示如下:

>>> sys.path

['', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages']


16、#sys.path.append进行追加路径,不过这个不是永久写入的,退出python就失效了。

>>> sys.path.append(r'c:\mydir')                                                                  

>>> sys.path                                                                                                                 

['', 'C:\\Program Files\\Python36-32\\python36.zip', 'C:\\Program Files\\Python36-32\\DLLs', 'C:\\Program Files\\Python36-32\

\lib', 'C:\\Program Files\\Python36-32', 'C:\\Program Files\\Python36-32\\lib\\site-packages', 'c:\\mydir']


17、#查看已经加载的模块函数命令

>>> sys.modules   

>>> sys                                                                                                                      

<module 'sys' (built-in)>                                                                                                    

>>> sys.modules['sys']                                                                                                       

<module 'sys' (built-in)> 


18、#使用sys.exc_info函数输出一个异常的元组信息


>>> try:                                                                                                                     

...     raise IndexError                                                                                                     

... except:                                                                                                                  

...     print(sys.exc_info())                                                                                                

...                                                                                                                          

(<class 'IndexError'>, IndexError(), <traceback object at 0x00D86288>) 


19、#traceback模块使用错误消息输出

>>> import traceback,sys                                                                                                     

>>> def grail(x):                                                                                                            

...     raise TypeError('already got one')                                                                                   

...                                                                                                                          

>>> try:                                                                                                                     

...     grail('arthur')                                                                                                      

... except:                                                                                                                  

...     exc_info = sys.exc_info()                                                                                            

...     print(exc_info[0])                                                                                                   

...     print(exc_info[1])                                                                                                   

...     traceback.print_tb(exc_info[2])                                                                                      

...                                                                                                                          

<class 'TypeError'>                                                                                                          

already got one                                                                                                              

  File "<stdin>", line 2, in <module>                                                                                        

  File "<stdin>", line 2, in grail  


20、#os模块的函数列举如下:

>>> import os                                                                                                           

>>> dir(os)                                                                                                             

['DirEntry', 'F_OK', 'MutableMapping', 'O_APPEND', 'O_BINARY', 'O_CREAT', 'O_EXCL', 'O_NOINHERIT', 'O_RANDOM', 'O_RDONLY

', 'O_RDWR', 'O_SEQUENTIAL', 'O_SHORT_LIVED', 'O_TEMPORARY', 'O_TEXT', 'O_TRUNC', 'O_WRONLY', 'P_DETACH', 'P_NOWAIT', 'P

_NOWAITO', 'P_OVERLAY', 'P_WAIT', 'PathLike', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'TMP_MAX', 'W_OK', 'X_OK', '_E

nviron', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spe

c__', '_execvpe', '_exists', '_exit', '_fspath', '_get_exports_list', '_putenv', '_unsetenv', '_wrap_close', 'abc', 'abo

rt', 'access', 'altsep', 'chdir', 'chmod', 'close', 'closerange', 'cpu_count', 'curdir', 'defpath', 'device_encoding', '

devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp

', 'execvpe', 'extsep', 'fdopen', 'fsdecode', 'fsencode', 'fspath', 'fstat', 'fsync', 'ftruncate', 'get_exec_path', 'get

_handle_inheritable', 'get_inheritable', 'get_terminal_size', 'getcwd', 'getcwdb', 'getenv', 'getlogin', 'getpid', 'getp

pid', 'isatty', 'kill', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'makedirs', 'mkdir', 'name', 'open', 'pardir', '

path', 'pathsep', 'pipe', 'popen', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'replace',

 'rmdir', 'scandir', 'sep', 'set_handle_inheritable', 'set_inheritable', 'spawnl', 'spawnle', 'spawnv', 'spawnve', 'st',

 'startfile', 'stat', 'stat_float_times', 'stat_result', 'statvfs_result', 'strerror', 'supports_bytes_environ', 'suppor

ts_dir_fd', 'supports_effective_ids', 'supports_fd', 'supports_follow_symlinks', 'symlink', 'sys', 'system', 'terminal_s

ize', 'times', 'times_result', 'truncate', 'umask', 'uname_result', 'unlink', 'urandom', 'utime', 'waitpid', 'walk', 'wr

ite']


21、#列举os.path的其他工具

>>> dir(os.path)                                                                                                        

['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_

get_bothseps', '_getfinalpathname', '_getfullpathname', '_getvolumepathname', 'abspath', 'altsep', 'basename', 'commonpa

th', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'generic

path', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists'

, 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep

', 'split', 'splitdrive', 'splitext', 'splitunc', 'stat', 'supports_unicode_filenames', 'sys']


22、#os.getpid()函数的进程ID、os.getcwd()和os.chdir()用法

>>> os.getpid()                        #给出调用函数的进程ID                                                                                                

3540                                                                                                                    

>>> os.getcwd()                      #返回当前工作目录                                                                                         

'C:\\'                                                                                                                  

>>> os.chdir(r'c:\\Users')        #进入Users工作目录                                                                                         

>>> os.getcwd()                     #返回当前工作目录                                                                                   

'c:\\Users'


23、#os的符号工具用法

>>> os.pathsep,os.sep,os.pardir,os.curdir,os.linesep                                                                    

(';', '\\', '..', '.', '\r\n') 


24、#os.path.isdir(是否是目录)和os.path.isfile(是否是文件)、os.path.exists(测试文件是否存在)、os.path.getsize(文件大小)

>>> os.path.isdir(r'c:\Users'),os.path.isfile(r'c:\users')                                                              

(True, False)                                                                                                                                                                                                               

>>> os.path.isdir(r'c:\windows\explorer.exe'),os.path.isfile(r'c:\windows\explorer.exe')                                

(False, True)                                                                                                           

>>> os.path.exists(r'c:\Users\Default') 

>>> os.path.getsize(r'c:\windows\explorer.exe')                                                                         

2872320


25、#分割和合并目录函数分别是os.path.split、os.path.join

os.path.dirname和os.path.basename是目录名和文件名输出

>>> os.path.split(r'c:\temp\data.txt')                                                                                  

('c:\\temp', 'data.txt')                                                                                                

>>> os.path.join(r'c:\temp','output.txt')                                                                               

'c:\\temp\\output.txt'                                                                                                  

>>> name = r'c:\temp\data.txt'                                                                                          

>>> os.path.dirname(name),os.path.basename(name)                                                                        

('c:\\temp', 'data.txt') 


26、#os.path.splitext文件名和后缀名进行分割

>>> os.path.splitext(r'c:\temp\data.txt')                                                                               

('c:\\temp\\data', '.txt')


27、#os.sep(输出双斜杠)

>>> os.sep                                                                                                              

'\\'                                                                                                                    

>>> pathname=r'c\temp\data.txt'                                                                                         

>>> os.path.split(pathname)                                                                                             

('c\\temp', 'data.txt')                                                                                                 

>>> pathname.split(os.sep)                                                                                              

['c', 'temp', 'data.txt']                                                                                               

>>> os.sep.join(pathname.split(os.sep))                                                                                 

'c\\temp\\data.txt'                                                                                                     

>>> os.path.join(*pathname.split(os.sep))                                                                               

'c\\temp\\data.txt' 


28、#os.path.abspath(返回文件完整路径名

>>> import os                                                                                     

>>> os.chdir(r'c:\Users')                                             

>>> os.getcwd()                                                                                   

'c:\\Users'                                                                                                             

>>> os.path.abspath('')                                                                                                 

'c:\\Users'                                                                                                             

>>> os.chdir(r'c:\windows')          

>>> os.path.abspath('temp')                                                                                             

'c:\\windows\\temp'                                                                                                                                                                                  

>>> os.path.abspath('.')                                #相对路径                                                                

'c:\\windows'                                                                       

>>> os.path.abspath('..')            

'c:\\'                                                              

>>> os.path.abspath(r'c:\windows\system')            #绝对路径                                             

'c:\\windows\\system' 


29、#os.system用法

>>> os.system('dir w* /B')                                                          

Web                                  

win.ini                                                                                                                 

WindowsUpdate.log                                                                                                       

winhlp32.exe                                                                        

winsxs                                   

WMSysPr9.prx                                                        

write.exe                                                                                         

0         



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随行之旅

python国产化自动化

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值