2016-02-12 21 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檢索結果中的橫幅和顏色。

相關問題