2013-02-13 87 views
1

我有內由本人調用一個python腳本一個shell腳本說new.py捕獲返回值到shell腳本

#!/usr/bin/ksh 

python new.py 

現在,這new.py是一樣的東西 -

if not os.path.exists('/tmp/filename'): 
    print "file does not exist" 
    sys.exit(0) 

如果該文件不存在,則python腳本將返回,但shell腳本將繼續執行。如果文件不存在,並且我的python腳本退出,我還想讓shell腳本停止。

請建議如何捕獲shell腳本中的返回以進一步停止執行。

回答

5

您需要從退出函數返回零以外的內容。

if os.path.exists("/tmp/filename"): 
    sys.exit(0) 
else: 
    sys.exit(1) 

錯誤值只有8位,所以只有整數的低8位返回到shell。如果提供負數,則將返回二進制補碼錶示的低8位,這可能不是您想要的。你通常不會返回負數。

+0

我現在正在返回sys.exit(-100),但在shell echo $中?給155 ...是否像這個數字分配給這種類型的錯誤,我可以安全地使用它,就像$? != 0然後退出shell – 2013-02-13 09:53:48

+0

@KundanKumar我更新了我對這個問題的回答。 – Keith 2013-02-13 09:58:45

+1

你也可以做'sys.exit(int(不是os.path.exists(「/ tmp/filename」)))',如果你願意的話 – 2013-02-13 10:11:00

5
if ! python new.py 
then 
    echo "Script failed" 
    exit 
fi 

這假設Python腳本使用sys.exit(0)當你的shell腳本應繼續sys.exit(1)(或其他非零值)時,應立即停止(這是習慣性地返回一個非零退出代碼發生錯誤時)。

相關問題