if shell is None: shell = 'an unknown command processor'
print('Running under', shell)
當一個Python程式變更它的環境(例如透過
os.environ['X']='Y'
),這並
不會影響啟動該程式的shell 或命令處理器的環境。如已經解說過的,而對
所有程式語言來說都是如此(包括Python):變更一個行程的環境只會影
響該行程本身,而不會影響目前執行中的其他行程。
執行其他程式
你可以透過
os
模組中的函式或使用(較高通常也較為偏好的抽象層)
subprocess
模組執行其他的程式。
以os模組執行其他程式
讓你的程式執行其他行程的最佳方式通常是使用
subprocess
模組,涵蓋於
後面的「subprocess 模組」。然而,
os
模組也提供了數種方式來這樣做,在
某些罕見的情況中,可能更為簡單。
執行另一個程式最簡單的方式是透過函式
os.system
,雖然這並不提供控制
外部程式的方式。
os
模組也提供數個名稱以
exec
開頭的函式。這些函式
提供了更精細的控制。由其中一個
exec
函式執行的程式會取代相同行程中
目前的程式(即Python 直譯器)。因此,在實務上,你主要會在能讓一個
行程藉由
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.