2012-06-15 167 views
0

如何執行shell命令,可以像bash命令行中的普通命令那樣複雜,在執行後獲取該命令和pwd的輸出?如何執行shell命令在Python中的命令後獲取輸出和pwd

我用這樣的功能:

import subprocess as sub 

def execv(command, path): 
    p = sub.Popen(['/bin/bash', '-c', command], 
        stdout=sub.PIPE, stderr=sub.STDOUT, cwd=path) 
    return p.stdout.read()[:-1] 

我檢查,如果用戶使用cd命令,但是當用戶使用符號連接到CD或其他奇怪的方式來改變目錄,將無法正常工作。

,我需要如果您使用subprocess.Popen持有{'cwd': '<NEW PATH>', 'result': '<COMMAND OUTPUT>'}

回答

0

我標準輸出重定向到pwd命令的標準錯誤。如果stdout是空的和stderr不是一個路徑,然後stderr是命令的錯誤

import subprocess as sub 

def execv(command, path): 
    command = 'cd %s && %s && pwd 1>&2' % (path, command) 
    proc = sub.Popen(['/bin/bash', '-c', command], 
        stdout=sub.PIPE, stderr=sub.PIPE) 
    stderr = proc.stderr.read()[:-1] 
    stdout = proc.stdout.read()[:-1] 
    if stdout == '' and not os.path.exists(stderr): 
     raise Exception(stderr) 
    return { 
     "cwd": stderr, 
     "stdout": stdout 
    } 

UPDATE:這裏是更好的FPGA實現(使用最後一行的PWD和不使用標準錯誤)

def execv(command, path): 
    command = 'cd %s && %s 2>&1;pwd' % (path, command) 
    proc = sub.Popen(['/bin/bash', '-c', command], 
        env={'TERM':'linux'}, 
        stdout=sub.PIPE) 
    stdout = proc.stdout.read() 
    if len(stdout) > 1 and stdout[-1] == '\n': 
     stdout = stdout[:-1] 
    lines = stdout.split('\n') 
    cwd = lines[-1] 
    stdout = '\n'.join(lines[:-1]) 
    return { 
     "cwd": cwd, 
     "stdout": man_to_ansi(stdout) 
    } 
1

一本字典,你應該得到一個管道對象,你可以communicate()該命令的輸出,並使用.pid()獲取進程的ID。我會真的感到驚訝,如果你不能找到一個方法來獲得由pid進程的當前工作目錄...

例如爲:http://www.cyberciti.biz/tips/linux-report-current-working-directory-of-process.html

+0

我試試吧,還有的/ proc//cwd目錄,代碼需要檢查,它可以使用'ls'或'file'(和解析結果)來做到這一點,但是當代碼執行那些命令時cwd不再可讀,因爲過程結束了。因此,您需要在執行命令後添加睡眠命令。更好的是隻是運行pwd。 – jcubic

1

爲了得到一個任意shell命令的輸出,其最終CWD(假設在CWD不換行):

from subprocess import check_output 

def command_output_and_cwd(command, path): 
    lines = check_output(command + "; pwd", shell=True, cwd=path).splitlines() 
    return dict(cwd=lines[-1], stdout=b"\n".join(lines[:-1]))