您的位置:首页 > 编程语言 > Python开发

《Python核心编程》第14章 执行环境 练习

2014-06-03 20:19 302 查看
14-3.执行环境。

创建运行其他Python脚本的脚本。
filename = raw_input('file name: ')
execfile(filename)14-4. os.system()。
调用os.system()运行程序。附加题:将你的解决方案移植到subprocess.call()。

import os
from subprocess import call

os.system('dir')
call('cmd /c dir')14-5. commands.getoutput()。
用commands.getoutput()解决前面的问题。

from commands import getoutput

output = getoutput('ls')
print output14-6.popen()家族。
选择熟悉的系统命令,该命令从标准输入获得文本,操作或输出数据。使用os.popen()与程序进行通信。

from os import popen

f = popen('dir')
for ch in f:
print ch,14-7.subprocess模块。
把先前问题的解决方案移植到subprocess模块。
from subprocess import check_output
ret = check_output('cmd /c dir')
print ret14-8.exit函数。
设计一个在程序退出时的函数,安装到sys.exitfunc(),运行程序,演示你的exit函数确实被调用了。

import sys

def foo():
print 'show message'

sys.exitfunc = foo
print '123'14-9.Shells.
创建shell(操作系统接口)程序。给出接受操作系统命令的命令行接口(任意平台)。

import os

while True:
cmd = raw_input('$: ')
if cmd == 'exit':
break

f = os.popen(cmd)
for line in f:
print line,
print
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 编程 脚本