Output shell command in python -


def run_command(command):     p = subprocess.popen(command,                          stdout=subprocess.pipe,                          stderr=subprocess.stdout)     return p.communicate() 

on running :

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

everything working.but when try run multiple commands got error.

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

use subprocess.check_output() shell=true option, heed security warning re untrusted inputs if applies you.

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 exc:     print("subprocess failed return code {}".format(exc.returncode))     print("message: {}".format(exc.message)) 

after output contains combined stdout of executed processes, if successful. otherwise need handle calledprocesserror exception.

alternatively, if can not guarantee command strings secure, can perform each command in turn, progressing next command if current command's return code 0 i.e. calledprocesserror not raised.

import subprocess import shlex  command = 'git clone www.myrepo.com/etc:etc && cd etc && git stash && git pull' output = [] try:     cmd in command.split('&&'):         output.append(subprocess.check_output(shlex.split(cmd))) except subprocess.calledprocesserror exc:     print("{!r} failed return code {}".format(' '.join(exc.cmd), exc.returncode)) else:     print(''.join(output)) 

while more secure regard shell command injection, still possible sensitive arguments sniffed other users example ps.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -