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() 会类似于抛出个异常


原创粉丝点击