如何在python脚本中检查bash测试命令的结果?

时间:2017-03-02 02:34:24

标签: python bash if-statement

我想在python脚本中运行bash“test”命令。

例如,在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  

上述方法是一个好方法吗?如果没有,那么请你建议一个合适的方式吗?

1 个答案:

答案 0 :(得分: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."