[英]os.system(<command>) execution through Python :: Limitations?
我正在編寫一個python(ver 2.7)腳本來自動化INOTOOL的入門示例中的命令集。
問題:當我運行整個腳本時,我反復遇到這些錯誤:
Current Directory is not empty
No project is found in this directory
No project is found in this directory
但是,當我運行第一個腳本時,直到標記的代碼行,並在接下來的三行中手動輸入,或者在我手動訪問之后運行最后三行(從“ino init -t blink”行開始) beep文件夾,然后我能夠成功執行相同的代碼。
我遇到的os.system()是否存在限制?
我的代碼:
import os,sys
def upload()
os.system("cd /home/pi/Downloads")
os.system("mkdir beep")
os.system("cd beep") #will refer to this code junction in question description
os.system("ino init -t blink")
os.system("ino build")
os.system("ino upload")
sys.exit(0)
是的,當為cd
運行os.system()
命令時,它實際上不會更改python進程上下文的當前目錄。 從文檔 -
使用os.system(命令)
在子shell中執行命令(字符串)。 這是通過調用標准C函數系統()來實現的,並且具有相同的限制。 對sys.stdin等的更改不會反映在已執行命令的環境中。
因此,即使您在os.system()調用中更改目錄,下一個os.system調用仍然發生在同一目錄中。 這可能會導致您的問題。
你應該嘗試使用os.chdir()
來改變目錄而不是os.system()
調用。
最好的是使用subprocess
進程模塊,因為@PadraicCunningham在他的回答中解釋道。
您可以使用子進程模塊和os.mkdir來創建目錄,您可以將當前工作目錄cwd
傳遞給check_call
以便您實際執行目錄中的命令:
from subprocess import check_call
import os
def upload():
d = "/home/pi/Downloads/beep"
os.mkdir(d)
check_call(["ino", "init", "-t", "blink"],cwd=d)
check_call(["ino", "build"],cwd=d)
check_call(["ino", "upload"],cwd=d)
非零退出狀態將引發您可能想要捕獲的CalledProcessError ,但一旦成功,您就會知道所有命令都返回0退出狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.