2017-01-01 30 views
1

我試圖從標準輸出參數比較已知字符串我有, 所以,如果有兩個字符串之間的匹配,它會給我退出代碼0, 而在如果不匹配,則以退出代碼1結束。從標準輸出比較參數字符串

我試圖從函數輸出插入stdout參數,但我得到一個錯誤。

這是我使用的代碼:

import subprocess 
from subprocess import check_output 

def pwd(): 
    pwdcmd = subprocess.call("pwd") 

out = check_output([pwd()]) 
print "this is where you are --> " + out 

從我讀過的和使用的命令相同的命令嘗試,而不是一個功能它的工作原理:

out = check_output(["pwd"]) 
print "this is where you are --> " + out 

如何將stdout放入函數的「out」參數中?

這是我的錯誤:

**

/opt/sign 
Traceback (most recent call last): 
    File "/opt/sign/test.py", line 15, in <module> 
    out = check_output([pwd()]) 
    File "/usr/lib64/python2.7/subprocess.py", line 568, in check_output 
    process = Popen(stdout=PIPE, *popenargs, **kwargs) 
    File "/usr/lib64/python2.7/subprocess.py", line 711, in __init__ 
    errread, errwrite) 
    File "/usr/lib64/python2.7/subprocess.py", line 1327, in _execute_child 
    raise child_exception 
AttributeError: 'NoneType' object has no attribute 'rfind' 
Process finished with exit code 1 

**

+0

你能給一個例子這意味着什麼*我想比較一個參數從標準輸出到已知的字符串我有,*。我在代碼中看不到任何比較結果。 –

+0

@MikeMüller我的問題不在於比較,而是從我的函數stdout中獲取參數給參數。 –

+0

我剛剛發佈的答案應該是你需要的。或者給你足夠的空間來做你在這個例子中做的其他事情。 –

回答

0

這是不是真的清楚你在做什麼。但是,這會工作:

import subprocess 

def pwd(): 
    return subprocess.check_output(["pwd"]) 

out = pwd() 
print "this is where you are --> " + out 

簡單:

import os 

print "this is where you are --> " + os.getcwd() 

第二種解決方案是平臺無關的,毫無疑問是如何解碼字節串子進程調用讓你在Python 3

+0

也許還不清楚,試圖從簡單的cmd,如'pwd'作品採取標準輸出。我的問題是,當從一個函數如下輸出標準輸出:out = check_output([function()]) –

+0

只是爲了澄清,你的目標是從您的腳本運行當前目錄?或者你打算用不同的命令來使用它,而pwd就是你選擇的例子。我問,因爲如果你想要的只是pwd的等價物,但是在python中,有很多更好的方法可以做到這一點。 –

+0

pwd只是一個示例命令,我想用它來測試它... –

0

這是一個使用subprocess.Popen而不是subprocess.call的方法,並且從list of lists而不是函數讀取您的命令。這應該給你你需要的東西:

import subprocess 

# This list contains a list for each command, with list[0] 
# being your desired output message, and list[1] being a list 
# containing a command and its arguments. 
command_list = [ 
        ["This is where you are -> ", ["pwd"]], 
        ["Here's what lives above this place:\n", ["ls","-larth", ".."]] 
] 

# Here we iterate through the list. 
for item in command_list: 

    # Execute your command using subprocess.Popen 
    with subprocess.Popen(item[1], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as proc: 

     # Assign its output to 'out' 
     out = proc.stdout.read() 

     # And print the message you have associated with the command, 
     # along with 'out', and any output from stdout andstderr 
     print(item[0], out) 
     print() 

希望這會有所幫助。新年快樂!