执行代码
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
本文介绍了Python中执行不同类型的代码的方法,包括使用eval、single、exec执行表达式或语句块,通过import导入模块并执行顶层代码,以及利用os和subprocess模块执行非Python程序。
1573

被折叠的 条评论
为什么被折叠?



