python调用shell命令并检查响应

2024-05-20 17:09:40 发布

您现在位置:Python中文网/ 问答频道 /正文

正在尝试编写一个函数,在做出决定之前读取shell命令的输出。。例如:

6 def getCreds():
  7         global access_key, secret_key, yourName
  8         access_key = raw_input("Enter Access Key: ")
  9         secret_key = raw_input("Enter Secret Key: ")
 10         infoCorrect = raw_input('Is this information correct? (y or n)')
 11         if infoCorrect.lower() == "yes" or infoCorrect.lower() =="y":
 12                 call (["./somecommand -u %s -p %s -flags" % (access_key, secret_key) +     tfdir],shell=True)
 13         else:

shell命令的输出是

"You have successfully logged in" 
or
"you cannot log in"

所以我不知道正确的语法:

if response = "You have successfully logged in" :
(some action)
elif:
(some action)

我该如何阅读回复?你知道吗

谢谢!你知道吗


Tags: orkeyin命令youinputsecretraw
2条回答

使用在subprocess中定义的Popen()方法并将输出重定向到PIPE。请尝试以下代码:

import subprocess

p = subprocess.Popen("ls", shell=True, stdout = subprocess.PIPE)
output,err = p.communicate()
print(output)

我认为shell命令的输出不能返回。您只能检查命令是否成功或返回错误。你知道吗

您可以将输出重定向到一个文件,然后检查其内容。你知道吗

    f = open("outputFile","wb")
    call (["./somecommand -u %s -p %s -flags" % (access_key, secret_key) +     tfdir],shell=True,stdout=f)

如果您想避免写入文件,那么您可能需要查看StringIO模块。你知道吗

相关问题 更多 >