Python语言的12个基础知识点小结

2019-10-06 11:56:03王旭

  0

使用 os.popen() 调用系统命令, 程序中可以获得命令输出,但是不能得到执行的返回值
>>> out = os.popen("ls -l /proc/cpuinfo")
>>> print out.read()
  -r--r--r-- 1 root root 0  3月 29 16:59 /proc/cpuinfo 

使用 commands.getstatusoutput() 调用系统命令, 程序中可以获得命令输出和执行的返回值
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
  (0, '/bin/ls')

11、Python 捕获用户 Ctrl+C ,Ctrl+D 事件

有些时候,需要在程序中捕获用户键盘事件,比如ctrl+c退出,这样可以更好的安全退出程序
try:
    do_some_func()
except KeyboardInterrupt:
    print "User Press Ctrl+C,Exit"
except EOFError:
    print "User Press Ctrl+D,Exit"

12、Python 读写文件

一次性读入文件到列表,速度较快,适用文件比较小的情况下
track_file = "track_stock.conf"
fd = open(track_file)
content_list = fd.readlines()
fd.close()
for line in content_list:
    print line 

逐行读入,速度较慢,适用没有足够内存读取整个文件(文件太大)
fd = open(file_path)
fd.seek(0)
title = fd.readline()
keyword = fd.readline()
uuid = fd.readline()
fd.close() 

写文件 write 与 writelines 的区别  

Fd.write(str) : 把str写到文件中,write()并不会在str后加上一个换行符
Fd.writelines(content) : 把content的内容全部写到文件中,原样写入,不会在每行后面加上任何东西