比较command.getoutput(cmd)的输出

时间:2011-02-18 10:01:02

标签: python

我有以下代码可以解决一个问题。我试图比较commands.getoutput(cmd)的两个输出,但我得到语法错误。我知道这可能本质上是错误的,但有人可能指出我做错了什么

def DiffGenerator():

  try: sys.argv[1]
  except: print "No Directory to scan defined\n"

  try: sys.argv[2]
  except: print "No delay time defined\n"

  ScanDirectory = sys.argv[1]
  if not os.path.exists(ScanDirectory):
    print "Scan Directory does not exist :" + ScanDirectory 

  cmd = "ls -l " + ScanDirectory

  try:
    DiffFileA = commands.getoutput(cmd)
    print "Printing DiffFileA" + DiffFileA
    time.sleep(1)
    DiffFileB = commands.getoutput(cmd)
    if operator.ne(DiffFileA, DiffFileB)
      print "New File placed within " + ScanDirectory
  except:
    print "BLAH"

2 个答案:

答案 0 :(得分:0)

您可能需要考虑子流程

http://docs.python.org/library/subprocess.html

subprocess.Popen(['ls','-a'], stdout = subprocess.PIPE, stdin = subprocess.PIPE)
results = subprocess.communicate()[0] #where [0] is the stdout and [1] is the stderr

编辑:

还可以请扩展你的尝试除了循环并使用特定的例外,例如。

为:

try: sys.argv[1]
except: print "No Directory to scan defined\n"

好:

try:
    sys.argv[1]
except IndexError:
    print "No directory to scan defined\n"

答案 1 :(得分:0)

if operator.ne(DiffFileA, DiffFileB)缺少一个冒号,可以解释一个SyntaxError。顺便说一句,在报告错误时,请复制并粘贴完全您看到的错误消息。

但是使用if operator.ne(A,B):如果A!= B:是一种非常简单的写法,我会避免它。