python os模組 程序處理

2021-06-05 07:20:47 字數 3009 閱讀 9378

使用 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 模組處理路徑

import os os 模組提供了非常豐富的方法用來處理檔案和目錄 1.用於返回當前工作目錄 dir name1 os.getcwd 列印 h pycharm projects lemon 20 homework print dir name1 dir name1 2.獲取作業系統名稱 print...

python os介紹 Python os模組介紹

os模組主要用於執行系統命令 import os os.remname file.txt file1.txt 檔案重新命名 os.remove file1.txt 刪除檔案 os.mkdir test 建立資料夾 os.rmdir test 刪除資料夾 os.sep 可以取代作業系統特定的路徑分割符...

python os模組總結

在python的標準庫os模組中包含普遍的作業系統功能。程式能夠與平台,就靠這個模組了。下面是os模組常用的方法.1.os.sep 可以取代作業系統特定的路徑分割符 2.os.name 字串指示你正在使用的平台。比如對於windows,它是 nt 而對於linux unix使用者,它是 posix ...