[Python]执行环境

来源:互联网 发布:钢琴 小提琴 知乎 编辑:程序博客网 时间:2024/06/03 13:15

一、可调用对象

可调用对象:任何能够通过函数操作符"()"来调用的对象。
Python有4种可调用对象:函数、方法、类、已经一些类的实例
1、函数
内建函数、用户定义函数、lambda表达式
2、方法
内建方法、用户定义方法
3、类
类是可以被调用的,调用类的结果是创建了实例。

>>> class C(object):    def __init__(self, *args):        print("Calling class C(), arguments:\n", args)>>> c1 = C()    # 调用类,类的实例化Calling class C(), arguments: ()>>> callable(c1)  # 类的实例是不可调用的False>>> c2 = C('haha', 666) # 调用类,类的实例化Calling class C(), arguments: ('haha', 666)>>> callable(c2)  # 类的实例是不可调用的False

4、类的实例
正常情况下类的实例是不可调用的。类的__call__方法运行用户创建可调用的对象(实例)。
默认情况下__call__()方法是没有实现的,如果在类定义中覆盖了这个方法,那么这个实例就成为可调用的。
调用这样的实例对象等同于调用__call__()方法。
>>> class D(object):    def __call__(self, *args):        print("I'm callable! Called with args:\n", args)>>> d = D()>>> callable(d)    # 实例d 是可调用的True>>> d()I'm callable! Called with args: ()>>> d('haha', 666)I'm callable! Called with args: ('haha', 666)
二、生成和执行代码对象(内建函数)

Python语句、赋值、表达式等这些可执行对象,无法像可调用物那样被调用。
这些可执行对象,必须先要转换成字节编译的代码(又称字节码),这个是代码对象。
(1)callable(obj)    # 如果obj可调用,返回True,否则返回False。
(2)compile(string, file, type)    # 从type类型中创建代码对象,file是代码存放的地方(通常设置为"")。
(3)eval(obj, globals=globals(), locals=locals()) 
                                                  # 对obj进行求值,obj是已编译为代码对象的表达式,或是一个字符串表达式;
                                                  # 可以给出全局或者/和局部的名称空间。
(4)exec(obj)        # 执行obj、单一的Python语句或者语句的集合(也就是说格式是代码对象或者字符串);
                              # obj也可以是一个文件对象(已经打开的有效的Python脚本中),在Python3中不能用。
(5)input(prompt="")      # 等同于 eval(raw_input(prompt="")) ,Python3中raw_input变成了input
                                         #Python2中 raw_input()返回一个列表的字符串描述,input()返回实际的列表。
1、compile()用法
compile(string, file, type)    # 编译成代码对象(或者叫编码对象 <class 'code'> code object)
其中string:要编译的Python代码;file:存放代码对象的文件名字(字符串类型,通常为"");
type:代码对象的类型;type有三种可能值:
(a)'eval' 可求值的表达式,与eval()一起使用。
(b)'single' 单一可执行语句,与exec()一起使用。
(c)'exec' 可执行语句组,与exec()一起使用。
# 可求值表达式>>> evalCode = compile('100 + 200', '', 'eval')>>> eval(evalCode)300>>> type(evalCode)  # 编码类型<class 'code'>>>> evalCode        # 编码对象<code object <module> at 0x03405F20, file "", line 1>
# 单一可执行语句>>> singleCode = compile('print("Hello World!")', '', 'single')>>> exec(singleCode)Hello World!>>> type(singleCode) # 编码类型<class 'code'>>>> singleCode       # 编码对象<code object <module> at 0x034056B0, file "", line 1>
# 可执行语句组>>> execCode = compile("""req = input('Count how many numbers?')for eachNum in range(int(req)):    print(eachNum)""", '', 'exec')>>> exec(execCode)Count how many numbers?501234
2、eval()用法
eval(obj, globals=globals(), locals=locals())   #对obj进行求值,obj是已编译为代码对象的表达式,或是一个字符串表达式;第二和第三个参数是可选的,第二个参数必须是字典,第三个参数是任意的映射对象。
>>> eval('666')      # 接受字符串并把它作为Python表达式进行求值666>>> int('666')       # 接受整型的字符串并把它转换为整型666>>> eval('10 + 20')  30>>> int('10 + 20')Traceback (most recent call last):  File "<pyshell#77>", line 1, in <module>    int('10 + 20')ValueError: invalid literal for int() with base 10: '10 + 20'  
3、exec()用法
exec(obj)        # 执行obj、单一的Python语句或者语句的集合(也就是说格式是代码对象或者字符串);
>>> exec("""x = 0print('x is currently:', x)while x < 5:  x += 1  print('incrementing x to:', x)  """)x is currently: 0incrementing x to: 1incrementing x to: 2incrementing x to: 3incrementing x to: 4incrementing x to: 5
4、input()用法
>>> aList = input('Enter a list: ')   # Python3中的input,返回的是字符串Enter a list: [123, 'abc', 'haha']>>> aList"[123, 'abc', 'haha']">>> type(aList)<class 'str'>>>> ab = eval(aList)                 # 执行之后返回的是list>>> type(ab)<class 'list'>  
三、执行Python程序

1、导入(import)
在第一次导入的时候会运行所有最高级别的Python代码(即没有缩进的)
# impOne.pyprint("loaded impOne")import impTwo
# impTwo.pyprint("loaded impTwo")def foo():    print("calling foo()")
>>> import impOneloaded impOneloaded impTwo
如果代码不想在导入的时候被执行,就缩进它并把它放在if __name__ == "__main__"的内部

# impOne.pyimport impTwoif __name__ == '__main__':        print("loaded impOne")
# impTwo.pydef foo():    print("calling foo()")if __name__ == "__main__":    print("loaded impTwo")
>>> import impOne>>>

# __name__模块的用法
如果模块是被导入的,__name__的值是模块的名字;
如果模块是被直接执行,__name__的值为'__main__'。
2、execfile(filename)  [Python2中使用]
3、将模块作为脚本执行
# myScript.pydef test():    print("calling the function test()")if __name__ == "__main__":    test()

$ python myScript.pycalling the function test()

四、执行非Python程序 [执行操作系统命令]

1、os.system()

>>> import os>>> ret = os.system('uname -a')Linux ubuntu 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux>>> ret    # 0 表示成功,非0 表示其他类型的错误0
2、os.popen()    # 文件对象和system()函数的结合

>>> import os>>> f = os.popen('uname -a')    # 返回一个类文件对象>>> data = f.readline()>>> f.close()>>> print(data)Linux ubuntu 4.4.0-75-generic #96-Ubuntu SMP Thu Apr 20 09:56:33 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux>>>
3、subprocess模块

>>> from subprocess import call>>> import os>>> ret = call(('cat', '/home/xl/tmp/myScript.py'))     # 替换os.system()def test():    print("calling the function test()")>>> ret0  


0 0
原创粉丝点击