比较command.getoutput(cmd)的输出

0 投票
2 回答
1019 浏览
提问于 2025-04-16 12:03

我有一段代码,基本上是能正常工作的,但有一个问题。我想比较两个命令的输出结果,使用的是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

这行代码 if operator.ne(DiffFileA, DiffFileB) 少了一个冒号,这可能是导致语法错误的原因。另外,当你报告错误的时候,请准确地复制并粘贴你看到的错误信息。

不过,用 if operator.ne(A,B): 这种写法其实不太符合 Python 的风格,建议还是用 if A != B: 这种更简单的方式。

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和except循环展开一下吗?并且使用具体的异常类型,比如:

不好的写法:

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"

撰写回答