python os模块 进程处理
来源:互联网 发布:seo网络优化人员待遇 编辑:程序博客网 时间:2024/06/04 23:22
使用 os 执行操作系统命令
import os
if os.name == "nt":
command = "dir"
else:
command = "ls -l"
os.system(command)
命令通过操作系统的标准 shell 执行, 并返回 shell 的退出状态. 需要注意的是在 Windows 95/98 下, shell 通常是 command.com
它的正常退出状态总是0.
使用 os 模块启动新进程
import os
import sys
program = "python"
arguments = ["hello.py"]
print os.execvp(program, (program,) + tuple(arguments))
print "goodbye"
hello again, and welcome to the show
Python 提供了很多表现不同的 exec 函数.使用的是 execvp 函数, 它会从标准路径搜索执行程序, 把第二个参数(元组)作为单独的参数传递给程序, 并使用当前的环境变量来运行程序.
在 Unix 环境下, 你可以通过组合使用 exec , fork 以及 wait 函数来从当前程序调用另一个程序.
fork 函数复制当前进程, wait 函数会等待一个子进程执行结束.
import os
import sys
def run(program, *args):
pid = os.fork() #fork 函数在子进程返回中返回 0
if not pid:
os.execvp(program, (program,) + args)
return os.wait()[0] #wait 函数会等待一个子进程执行结束.
run("python", "hello.py")
print "goodbye"
hello again, and welcome to the show
goodbye
fork 函数在子进程返回中返回 0 (这个进程首先从 fork 返回值), 在父进程中返回一个非 0 的进程标识符(子进程的 PID ).
也就是说, 只有当我们处于子进程的时候 "not pid" 才为真.
fork 和 wait 函数在 Windows 上是不可用的, 但是你可以使用 spawn 函数.
不过, spawn 不会沿着路径搜索可执行文件, 你必须自己处理好些.
import os
import string
def run(program, *args):
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + ".exe"
try:
return os.spawnv(os.P_WAIT, file, (file,) + args)
except os.error:
pass
raise os.error, "cannot find executable"
run("python", "hello.py")
print "goodbye"
hello again, and welcome to the show
goodbye
Unix 系统中, 你可以使用 fork 函数把当前进程转入后台(一个"守护者/daemon").
一般来说, 你需要派生(fork off)一个当前进程的副本, 然后终止原进程
使用 os 模块使脚本作为守护执行 (Unix)
import os
import time
pid = os.fork()#fork 函数在子进程返回中返回 0 , 在父进程中返回一个非 0 的进程标识符(子进程的 PID ).
if pid:
os._exit(0) # kill original
print "daemon started"
time.sleep(10)
print "daemon terminated"
使用 os 模块终止当前进程
try:
sys.exit(1) #抛出异常
except SystemExit, value: #被捕获不做退出操作
print "caught exit(%s)" % value
try:
os._exit(2) #直接退出不抛出异常
except SystemExit, value: #捕获无效
print "caught exit(%s)" % value
print "bye!"
caught exit(1)
先前例子中的 _exit 函数会终止当前进程. 而 sys.exit 不同, 如果调用者(caller) 捕获了 SystemExit 异常, 程序仍然会继续执行.
os._exit() 程序会直接结束 而使用sys.exit() 会类似于抛出个异常
- python os模块 进程处理
- Python:OS 模块 -- 进程管理
- python os模块进程函数
- os模块:处理文件,文件夹,进程
- Python:os模块的进程管理
- Python之OS模块进程管理介绍--os.fork()
- Python之OS模块进程管理介绍--os.fork()
- python基础-random、os模块、异常处理模块
- Python之os模块的进程管理介绍
- Python之os模块的进程管理介绍
- python os.path模块/Python os.listdir/字符串处理/python 时间datetime.datetime
- python学习之os.path模块&&elementtree处理xml文件
- python中os模块的常见处理函数
- Python学习OS 模块来处理文件和目录
- Python 模块学习:os模块
- Python 模块学习:os模块
- Python 模块学习:os模块
- Python 模块学习:os模块
- 多个字符作为分割符
- 查看或配置 backup compression default 服务器配置选项(默认是否压缩备份)
- Draw something现象
- 八款Js框架介绍及比较
- Linux文件/文件夹管理
- python os模块 进程处理
- linux mips启动分析
- 高效删除Oracle数据库中重复数据的方法 .
- PE文件格式学习心得【1】
- Excel有用的函数(ISBLANK,IF,LEFT,VALUE)
- 分享 35 套精美的 PSD 图标素材
- 记一次ORA-00600 [kope2_readstr232和ORA-07445[_ptrgl] [SIGSEGV] [Invalid permissions for mapped object]
- SmartClient
- 一周最新示例代码回顾 (3/19–3/25)