python如果语句打印不正确的条件

时间:2016-11-04 03:29:25

标签: python python-2.7

有人可以帮助我解决我在这里做错的事吗?

  root@localhost:$ cat Names
                   This is Paul

这是我的python脚本

from subprocess import *
test = check_output("grep Paul Names", stderr=STDOUT, shell=True )

if test is True :
  print ("Correct")
else:
  print("Incorrect")

结果

 root@localhost:$ python find.py
                  Incorrect

这应该打印正确。

4 个答案:

答案 0 :(得分:2)

变量test将包含该命令生成的标准输出。 看看这个例子:

from subprocess import *
test = check_output("echo test", stderr=STDOUT, shell=True )
assert test == 'test\n'

要测试变量是否为空,您可以这样做:

if test:

test=''将失败且test='anything else'将通过。

答案 1 :(得分:2)

看起来代码的意图是打印"正确"如果"保罗"在文件中找到,"不正确"否则。

即使您将if test is True:替换为if test:,您的代码也不适用于" Paul"在文件中找不到 。在这种情况下,check_output会引发subprocess.CalledProcessError因为grep的退出代码非零。

相反,您可以使用subprocess.call并直接检查grep的退出代码。使用stdout=PIPE来抑制grep的输出。

from subprocess import *
exit_code = call("grep Paul Names", stdout=PIPE, stderr=PIPE, shell=True)
if exit_code == 0:
    print("Correct")
else:
    print("Incorrect")

答案 2 :(得分:1)

使用is身份运算符,因此它不会执行认为的比较。它会比较,看看你是否指向同一个对象。

您的支票应该是:

if test:

答案 3 :(得分:0)

最好将check_output放在try-except块中,因为如果命名文件存在于文件系统中,则子进程会抛出错误。抓住它并正确操作

from subprocess import *
try:
    test = check_output("grep a ax.py", shell=True )
    if test:
        print("correct")
    else:
        print("incorrect")
except CalledProcessError as err:
    print(err)
相关问题