python学习笔记(三)

执行代码

1.执行python代码

eval, single, exec三种类型

 

exp = compile('1+2', '', 'eval');

eval(exp);

 

exp = compile('1+2', '', 'single');

eval(exp);

 

exp = compile('''

for i in range(1,10):

    print i;

''', '', 'exec');

exec exp;

 

2. 执行module代码

 

import moduleName;

上面的语句会执行模块中的所有顶层代码,比如有么一个模块:

 

test.py

-------------------

def method1():

    print 'method1';

 

print 'test module';

 

if __name__ == '__main__':

    print 'main module';

 

imort的结果是输出:test module

因为import的时候,其__name__其实还是模块名本身,而不是__main__,因而if语句并不会被执行。

 

而:

execfile('test.py');

将会输出:

test module

main module

因为它是在当前的主模块中运行代码的。

 

 

P.S. 原来python内置了一个CGI的HTTP SERVER。

 

import CGIHTTPServer;

CGIHTTPServer.test();

 

或者:

python -c "import CGIHTTPServer; CGIHTTPServer.test();"

 

3. 执行非Python程序

a. os.system()

e.g.,

import os;

ret = os.system('dir'); ## windows

ret = os.system('uname -r'); ## linux

其中ret为命令的返回值,对于windows,总是返回0

 

b. os.popen()

跟上面命令的作用是一样的,只不过不直接将结果在屏幕中输出,而是放到一个类似于file的object中作为返回值。可以用readline读取。

e.g.,

ret = os.popen('dir');

print ret.readline();

ret.close()

 

c. subprocess.call

from subprocess import call;

ret = call(('dir', 'C:/'), shell=True);

 

..还有很多。。。

spawn*

exec*

fork

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值