在python中输出shell命令

时间:2016-01-16 00:38:52

标签: python shell subprocess

def run_command(command):
    p = subprocess.Popen(command,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    return p.communicate()

跑步时:

   command = ("git clone " + repo).split()
    run_command(commmnd)

一切正常。但是当我尝试运行多个命令时,我收到了一个错误。

command = ("git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull).split()
run_command(command)

1 个答案:

答案 0 :(得分:0)

subprocess.check_output()import subprocess command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull' try: output = subprocess.check_output(command, shell=True) except subprocess.CalledProcessError as exc: print("subprocess failed with return code {}".format(exc.returncode)) print("message: {}".format(exc.message)) 选项一起使用,但如果适用于您,请注意安全警告不受信任的输入。

output

CalledProcessError包含已执行进程的组合stdout后,如果成功。否则,您需要处理CalledProcessError例外。

或者,如果您不能保证命令字符串是安全的,则可以依次执行每个命令,仅当当前命令的返回码为0时才进入下一个命令,即不引发import subprocess import shlex command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull' output = [] try: for cmd in command.split('&&'): output.append(subprocess.check_output(shlex.split(cmd))) except subprocess.CalledProcessError as exc: print("{!r} failed with return code {}".format(' '.join(exc.cmd), exc.returncode)) else: print(''.join(output)) 。 / p>

ps

虽然这对于shell命令注入更安全,但是敏感参数仍然可以被其他用户嗅探,例如使用Region smallestFittingFreeRegion = FreeRegions .Where(region => region.Rect.W >= width && region.Rect.H >= height) .MinBy(region => (region.Rect.W - width) * (region.Rect.H - height));

相关问题