module

 扯淡的人

 

不被调用的    要写在这下面

1 1 if __name__=="__main__":

import  调用同级目录的模块

1 import item

 

当前文件  在pyCharm里变成当前的路径

1 print(__file__)
2 >>>F:/文文/101010/练习/模块/os.py

拿到当前上一级的路径   并添加环境变量   可调用上一级的自定义模块   

1 import sys,os
2 BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
3 sys.path.append(BASE_DIR)

临时修改 环境变量

1 import sys
2 sys.path.append(path)

sys

.version   获得解释器的版本

import sys,os
print(sys.version)
>>>3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)]

.platform   显示操作系统平台

1 import sys,os
2 print(sys.platform)
3 >>>win32

.stdout.write()   可打印多个

1 import sys
2 sys.stdout.write("#")
3 sys.stdout.write("#")
4 >>>##

.stdout.flush()   直接从内存刷新到硬盘

import sys
sys.stdout.flush()

进度条     

import sys,time
for i in range(10):
    sys.stdout.write("#")
    time.sleep(0.1)
    sys.stdout.flush()
>>>##########

.argv   命令行参数List,第一个元素是程序本身路径

.path   返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值

.maxint  最大的int值

终端乱码问题

import os, platform
if platform.system()=="Windows":
    os.system('chcp 65001')

 

shelve

创建并取值

1 import shelve
2 f=shelve.open(r"shelve1")
3 # f["stu1_info"]={"name":"alex","age":"18"}
4 # f["stu2_info"]={"name":"alvin","age":"20"}
5 # f["school_info"]={"website":"oldboy.com","city":"beijing"}
6 # f.close()
7 print(f.get("stu1_info")["age"])
8 >>>18
shelve是一额简单的数据存储方案,他只有一个函数就是open(),这个函数接收一个参数就是文件名,然后返回一个shelf对象,你可以用他来存储东西,就可以简单的把他当作一个字典,当你存储完毕的时候,就调用close函数来关闭
这个有一个潜在的小问题,如下:
>>> import shelve  
>>> s = shelve.open('test.dat')  
>>> s['x'] = ['a', 'b', 'c']  
>>> s['x'].append('d')  
>>> s['x']  
['a', 'b', 'c']  

存储的d到哪里去了呢?其实很简单,d没有写回,你把['a', 'b', 'c']存到了x,当你再次读取s['x']的时候,s['x']只是一个拷贝,而你没有将拷贝写回,所以当你再次读取s['x']的时候,它又从源中读取了一个拷贝,所以,你新修改的内容并不会出现在拷贝中,解决的办法就是,第一个是利用一个缓存的变量,如下所示

>>> temp = s['x']  
>>> temp.append('d')  
>>> s['x'] = temp  
>>> s['x']  
['a', 'b', 'c', 'd']  

在python2.4中有了另外的方法,就是把open方法的writeback参数的值赋为True,这样的话,你open后所有的内容都将在cache中,当你close的时候,将全部一次性写到硬盘里面。如果数据量不是很大的时候,建议这么做。

 

configparser模块(* *)

来看一个好多软件的常见文档格式如下:

[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
  
[bitbucket.org]
User = hg
  
[topsecret.server.com]
Port = 50022
ForwardX11 = no

如果想用python生成一个这样的文档怎么做呢?

import configparser
  
config = configparser.ConfigParser()    #生成文件对象
config["DEFAULT"] = {'ServerAliveInterval': '45',    #创建一个字典,在下面创建三条数据
                      'Compression': 'yes',
                     'CompressionLevel': '9'}
  
config['bitbucket.org'] = {}    #创建一个字典
config['bitbucket.org']['User'] = 'hg'    #字典下面的数据
config['topsecret.server.com'] = {}    #创建一个字典
topsecret = config['topsecret.server.com']    #拿到这个字典
topsecret['Host Port'] = '50022'     # mutates the parser    #给字典赋值
topsecret['ForwardX11'] = 'no'  # same here    #给字典赋值
config['DEFAULT']['ForwardX11'] = 'yes'<br>

with open('example.ini', 'w') as configfile:    #打开文件对象
   config.write(configfile)    #写入文件里

 

import configparser

config = configparser.ConfigParser()    #拿到这个对象

#---------------------------------------------查
print(config.sections())   #[]    #打印下面有几个快(字典的意思)

config.read('example.ini')    #把文件读进来,arg=文件名

print(config.sections())   #['bitbucket.org', 'topsecret.server.com']    #不打印默认的块

print('bytebong.com' in config)# False  #判断在不在,不存在就False

print(config['bitbucket.org']['User']) # hg    #打印块下面的信息

print(config['DEFAULT']['Compression']) #yes    #取值

print(config['topsecret.server.com']['ForwardX11'])  #no


for key in config['bitbucket.org']:    #便利块(字典)取数据,会获取[DEFAULT]下面的信息
    print(key)


# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11


print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.items('bitbucket.org'))  #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]

print(config.get('bitbucket.org','compression'))#yes


#---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))


config.add_section('yuan')

config.remove_section('topsecret.server.com')
config.remove_option('bitbucket.org','user')

config.set('bitbucket.org','k1','11111')

config.write(open('i.cfg', "w"))

 hashlib

import time
import hashlib

ha = hashlib.md5(self.key.encode('utf-8'))#KEY = '299095cc-1330-11e5-b06a-a45e60bec08b'
        time_span = time.time()
        ha.update(bytes("%s|%f" % (self.key, time_span), encoding='utf-8'))
        encryption = ha.hexdigest()
        result = "%s|%f" % (encryption, time_span)
        return {self.key_name: result}

 

 

系统命令

可以执行shell命令的相关模块和函数有:

  • os.system
  • os.spawn*
  • os.popen*          --废弃
  • popen2.*           --废弃
  • commands.*      --废弃,3.x中被移除
import commands

result = commands.getoutput('cmd')
result = commands.getstatus('cmd')
result = commands.getstatusoutput('cmd')

以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能。

call 

执行命令,返回状态码

ret = subprocess.call(["ls", "-l"], shell=False)
ret = subprocess.call("ls -l", shell=True)

check_call

执行命令,如果执行状态码是 0 ,则返回0,否则抛异常

subprocess.check_call(["ls", "-l"])
subprocess.check_call("exit 1", shell=True)

check_output

执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常

subprocess.check_output(["echo", "Hello World!"])
subprocess.check_output("exit 1", shell=True)

  

 

subprocess.Popen(...)

用于执行复杂的系统命令

参数:

    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo与createionflags只在windows下有效
      将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

 

import subprocess
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

 

终端输入的命令分为两种:

  • 输入即可得到输出,如:ifconfig
  • 输入进行某环境,依赖再输入,如:python
import subprocess

obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)
View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
obj.stdin.close()

cmd_out = obj.stdout.read()
obj.stdout.close()
cmd_error = obj.stderr.read()
obj.stderr.close()

print(cmd_out)
print(cmd_error)
View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")

out_error_list = obj.communicate()
print(out_error_list)
View Code
import subprocess

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out_error_list = obj.communicate('print("hello")')
print(out_error_list)
View Code

 

开进程调用脚本  #当前脚本不阻塞

import json
from web import models
import subprocess
from django import conf

task_script="python %s/backend/task_runner.py %s"%(conf.settings.BASE_DIR,task_obj.id)
        cmd_process=subprocess.Popen(task_script,shell=True)

 这个模块一个类:Popen。

#Popen它的构造函数如下:
 
subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None,stderr=None, preexec_fn=None, close_fds=False, shell=False,<br>                 cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)
# 参数args可以是字符串或者序列类型(如:list,元组),用于指定进程的可执行文件及其参数。
# 如果是序列类型,第一个元素通常是可执行文件的路径。我们也可以显式的使用executeable参
# 数来指定可执行文件的路径。在windows操作系统上,Popen通过调用CreateProcess()来创
# 建子进程,CreateProcess接收一个字符串参数,如果args是序列类型,系统将会通过
# list2cmdline()函数将序列类型转换为字符串。
# 
# 
# 参数bufsize:指定缓冲。我到现在还不清楚这个参数的具体含义,望各个大牛指点。
# 
# 参数executable用于指定可执行程序。一般情况下我们通过args参数来设置所要运行的程序。如
# 果将参数shell设为True,executable将指定程序使用的shell。在windows平台下,默认的
# shell由COMSPEC环境变量来指定。
# 
# 参数stdin, stdout, stderr分别表示程序的标准输入、输出、错误句柄。他们可以是PIPE,
# 文件描述符或文件对象,也可以设置为None,表示从父进程继承。
# 
# 参数preexec_fn只在Unix平台下有效,用于指定一个可执行对象(callable object),它将
# 在子进程运行之前被调用。
# 
# 参数Close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会
# 继承父进程的输入、输出、错误管道。我们不能将close_fds设置为True同时重定向子进程的标准
# 输入、输出与错误(stdin, stdout, stderr)。
# 
# 如果参数shell设为true,程序将通过shell来执行。
# 
# 参数cwd用于设置子进程的当前目录。
# 
# 参数env是字典类型,用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父
# 进程中继承。
# 
# 参数Universal_newlines:不同操作系统下,文本的换行符是不一样的。如:windows下
# 用’/r/n’表示换,而Linux下用’/n’。如果将此参数设置为True,Python统一把这些换行符当
# 作’/n’来处理。
# 
# 参数startupinfo与createionflags只在windows下用效,它们将被传递给底层的
# CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等。

简单命令:

import subprocess
 
a=subprocess.Popen('ls')#  创建一个新的进程,与主进程不同步
 
print('>>>>>>>',a)#a是Popen的一个实例对象
 
'''
>>>>>>> <subprocess.Popen object at 0x10185f860>
__init__.py
__pycache__
log.py
main.py
 
'''
 
# subprocess.Popen('ls -l',shell=True)
 
# subprocess.Popen(['ls','-l'])

subprocess.PIPE

在创建Popen对象时,subprocess.PIPE可以初始化stdin, stdout或stderr参数。表示与子进程通信的标准流。

import subprocess
 
# subprocess.Popen('ls')
p=subprocess.Popen('ls',stdout=subprocess.PIPE)#结果跑哪去啦?
 
print(p.stdout.read())#这这呢:b'__pycache__\nhello.py\nok.py\nweb\n'

这是因为subprocess创建了子进程,结果本在子进程中,if 想要执行结果转到主进程中,就得需要一个管道,即 : stdout=subprocess.PIPE

subprocess.STDOUT

创建Popen对象时,用于初始化stderr参数,表示将错误通过标准输出流输出。

Popen的方法

Popen.poll() 
用于检查子进程是否已经结束。设置并返回returncode属性。

Popen.wait() 
等待子进程结束。设置并返回returncode属性。

Popen.communicate(input=None)
与子进程进行交互。向stdin发送数据,或从stdout和stderr中读取数据。可选参数input指定发送到子进程的参数。 Communicate()返回一个元组:(stdoutdata, stderrdata)。注意:如果希望通过进程的stdin向其发送数据,在创建Popen对象的时候,参数stdin必须被设置为PIPE。同样,如 果希望从stdout和stderr获取数据,必须将stdout和stderr设置为PIPE。

Popen.send_signal(signal) 
向子进程发送信号。

Popen.terminate()
停止(stop)子进程。在windows平台下,该方法将调用Windows API TerminateProcess()来结束子进程。

Popen.kill()
杀死子进程。

Popen.stdin 
如果在创建Popen对象是,参数stdin被设置为PIPE,Popen.stdin将返回一个文件对象用于策子进程发送指令。否则返回None。

Popen.stdout 
如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回 None。

Popen.stderr 
如果在创建Popen对象是,参数stdout被设置为PIPE,Popen.stdout将返回一个文件对象用于策子进程发送指令。否则返回 None。

Popen.pid 
获取子进程的进程ID。

Popen.returncode 
获取进程的返回值。如果进程还没有结束,返回None。
View Code

supprocess模块的工具函数

supprocess模块提供了一些函数,方便我们用于创建进程来实现一些简单的功能。
 
subprocess.call(*popenargs, **kwargs)
运行命令。该函数将一直等待到子进程运行结束,并返回进程的returncode。如果子进程不需要进行交 互,就可以使用该函数来创建。
 
subprocess.check_call(*popenargs, **kwargs)
与subprocess.call(*popenargs, **kwargs)功能一样,只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常。在异常对象中,包 括进程的returncode信息。
 
check_output(*popenargs, **kwargs)
与call()方法类似,以byte string的方式返回子进程的输出,如果子进程的返回值不是0,它抛出CalledProcessError异常,这个异常中的returncode包含返回码,output属性包含已有的输出。
 
getstatusoutput(cmd)/getoutput(cmd)
这两个函数仅仅在Unix下可用,它们在shell中执行指定的命令cmd,前者返回(status, output),后者返回output。其中,这里的output包括子进程的stdout和stderr。
import subprocess

#1
# subprocess.call('ls',shell=True)
'''
hello.py
ok.py
web
'''
# data=subprocess.call('ls',shell=True)
# print(data)
'''
hello.py
ok.py
web
0
'''

#2
# subprocess.check_call('ls',shell=True)

'''
hello.py
ok.py
web
'''
# data=subprocess.check_call('ls',shell=True)
# print(data)
'''
hello.py
ok.py
web
0
'''
# 两个函数区别:只是如果子进程返回的returncode不为0的话,将触发CalledProcessError异常



#3
# subprocess.check_output('ls')#无结果

# data=subprocess.check_output('ls')
# print(data)  #b'hello.py\nok.py\nweb\n'
演示

 

posted @ 2016-12-15 10:30  陨落&新生  阅读(332)  评论(0编辑  收藏  举报