2017-03-02 33 views
0

我想在python腳本中運行bash「test」命令。如何檢查Python腳本中的bash測試命令的結果?

例如,在bash銷售腳本中,這可以輕鬆完成,如下所示。 ! #/斌/慶典

if ! test -s ${file}; then 
    echo "${file} does not have a positive size. " 
    # Do some processing.. 
fi 

用Python腳本,我想我可以嘗試以下方法:

#!/usr/bin/python 
import subrocess 

try: 
    subprocess.check_call("test -s " + file, shell=True) 
except: 
    print file + " does not have a positive size. " 
    # Do some process 

是上述辦法的好辦法?如果沒有,那麼你能否建議一個適當的方法?

回答

2

除非有必要,否則不應使用shell=True。在這裏,您可以使用subprocess.check_call(["test","-s",file]),而沒有shell=True的安全缺陷。

除此之外,您可以使用python的內置函數而不是進行子流程調用。例如,os有你想要的:

import os 
try: 
    if os.stat(file).st_size == 0: 
     print "File empty." 
except OSError: 
    print "File could not be opened."