0

シェルコマンドを実行するにはどうすればよいですか? bash コマンドラインの通常のコマンドのように複雑になる可能性があり、実行後にそのコマンドと 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 へのシンボリックリンクまたはその他の奇妙な方法でディレクトリを変更すると、それは機能しません。

そして、私は保持する辞書が必要です{'cwd': '<NEW PATH>', 'result': '<COMMAND OUTPUT>'}

4

3 に答える 3

1

最後の 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]))
于 2013-07-25T21:23:29.807 に答える
1

を使用する場合は、コマンド出力に使用subprocess.Popenできるパイプ オブジェクトを取得し、プロセス ID を取得するために使用する必要があります。プロセスの現在の作業ディレクトリをpidで取得する方法が見つからない場合は、本当に驚くでしょう...communicate().pid()

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

于 2012-06-15T09:53:11.577 に答える
0

stdout を pwd コマンドの stderr にリダイレクトします。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
    }

更新: これはより良い実装です (pwd の最後の行を使用し、stderr を使用しないでください)

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)
    }
于 2012-06-15T10:37:59.687 に答える