2016-02-12 69 views
0

我正在编写一个脚本来从指定的路径中提取某些东西。我将这些值返回给一个变量。我如何检查shell命令是否返回了一些或什么都没有。如何检查一个shell命令是否返回什么或什么

我的代码:

def any_HE(): 
    global config, logger, status, file_size 
    config = ConfigParser.RawConfigParser() 
    config.read('config2.cfg') 
    for section in sorted(config.sections(), key=str.lower): 
     components = dict() #start with empty dictionary for each section 
    #Retrieving the username and password from config for each section 
     if not config.has_option(section, 'server.user_name'): 
      continue 
     env.user = config.get(section, 'server.user_name') 
     env.password = config.get(section, 'server.password') 
     host = config.get(section, 'server.ip') 
     print "Trying to connect to {} server.....".format(section) 

     with settings(hide('warnings', 'running', 'stdout', 'stderr'),warn_only=True, host_string=host): 
      try: 
       files = run('ls -ltr /opt/nds') 
       if files!=0: 
        print '{}--Something'.format(section) 
       else: 
        print '{} --Nothing'.format(section) 
      except Exception as e: 
       print e 

我试图检查1或0,是真是假,但似乎没有奏效。在某些服务器中,路径“/ opt/nds /”不存在。所以在这种情况下,文件上没有任何东西。我想区分返回到文件的东西,而不是返回到文件。

+5

究竟是“运行”? – poke

+0

您需要使用'subprocess'模块来管理您的流程。看看[subprocess documentation](https://docs.python.org/2/library/subprocess.html)。 – perror

+0

你的缩进被破坏,这段代码永远不会运行。 – 2016-02-12 11:22:13

回答

1

plumbum是一个很棒的库,用于从python脚本运行shell命令。例如:

from plumbum.local import ls 
from plumbum import ProcessExecutionError 
cmd = ls['-ltr']['/opt/nds'] # construct the command 
try:  
    files = cmd().splitlines() # run the command 
    if ...: 
     print ...: 
except ProcessExecutionError: 
    # command exited with a non-zero status code 
    ... 

在此基础上使用的顶部(与不同于subprocess模块),它也支持之类的东西输出重定向和命令流水线,更多的,与简单,直观的语法(通过重载蟒运算符,如'|'为管道)。

0

为了更好地控制您运行的过程,您需要使用subprocess模块。

下面是代码的例子:

import subprocess 
task = subprocess.Popen(['ls', '-ltr', '/opt/nds'], stdout=subprocess.PIPE) 
print task.communicate() 
1

由于PERROR已经评论说,蟒蛇子模块提供合适的工具。 https://docs.python.org/2/library/subprocess.html

对于您的特定问题,您可以使用check_output函数。 文档给出了下面的例子:

import subprocess 
subprocess.check_output(["echo", "Hello World!"]) 

给出的 “Hello World”

+0

A.L. ......有没有其他的方法来检查是否有任何东西被返回。现在我不想更改代码,因为有那么多功能。 –

2

首先,你隐藏stdout。 如果你摆脱了这一点,你会得到一个字符串与远程主机上的命令的结果。然后,您可以将它拆分为os.linesep(假设使用相同的平台),但您还应该处理其他内容,例如SSH检索结果中的横幅和颜色。

相关问题