how to run linux command with multi pipes by python !! - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: how to run linux command with multi pipes by python !! (/thread-32163.html) |
how to run linux command with multi pipes by python !! - evilcode1 - Jan-25-2021 hey all .. i am trying to run this command on my machine by using python subprocess module ... command : ping -c 1 -t 1 -w 1 192.168.1.81 | grep "ttl=" | awk {'print $4'} | sed 's/.$//'code import subprocess q= subprocess.run(['ping', '-c' ,'1' ,'192.168.1.81' , '| grep ttl' , ' awk {"print $4"}' , " sed 's/.$//'"], capture_output=True) print(q.stdout.decode())i dont get an error i just get an empty result !! RE: how to run linux command with multi pipes by python !! - Axel_Erfurt - Jan-25-2021 try import subprocess q= subprocess.check_output("ping -c 1 -t 1 -w 1 192.168.1.81 | grep 'ttl=' | awk {'print $4'} | sed 's/.$//'", shell=True) print(q.decode()) RE: how to run linux command with multi pipes by python !! - DeaD_EyE - Jan-25-2021 import shlex from subprocess import PIPE, Popen def run_pipes(cmds): """ Run commands in PIPE, return the last process in chain """ cmds = map(shlex.split, cmds) first_cmd, *rest_cmds = cmds procs = [Popen(first_cmd, stdout=PIPE)] for cmd in rest_cmds: last_stdout = procs[-1].stdout proc = Popen(cmd, stdin=last_stdout, stdout=PIPE) procs.append(proc) return procs[-1] cmds = [ "ping -c1 5.9.16.40", "grep ttl", "awk '{print $4}'", "sed 's/.$//'", ] last_proc = run_pipes(cmds) stdout = last_proc.stdout for line in stdout: line = line.decode() print(line, end="")The function shlex.split splits a string like the shell is doing it. This is useful to split the command. Using shell=True is not so good because it makes vulnerabilities possible. This part here, can be done with Python instead of rely on os dependend tools. For example, grep , awk and sed are not installed on Windows.grep 'ttl=' | awk {'print $4'} | sed 's/.$//'"The ping command itself could still be used because it's almost everywhere available. Some options differs from implementation to implementation. So Windows-Ping has for example some different options. |