2017-03-02 31 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."