Getting execution of a command returning an input channel

I have this Python 3 code stored in pipe.pywhich takes some input channel and prints it in turn:

import sys

for i, line in enumerate(sys.stdin):
    print("{}: {}".format(i, line))

Then I can run this in Bash:

$ echo "Test" | python pipe.py
0: Test

This works as planned, but I am wondering if there is a way to actually run the command run that led to the inbound channel. So, for my example above, the value Testwas sent to the program, but echo "Test"was executed to get this value.

Is there a way to get this command echo "Test"as a string in my Python program?

+4
source share
1 answer

- , Linux, /proc, a) stdin - , b) .

/proc :

  • Python script , stdin ( 0).
  • stdout (1) .

, Python script 1001, pid 1000, , :

$ ls -l /proc/1001/fd/0
lr-x------ 1 user users 64 Sep 22 14:41 /proc/1001/fd/0 -> 'pipe:[507536]'

$ ls -l /proc/1000/fd/1
l-wx------ 1 user users 64 Sep 22 14:41 /proc/1000/fd/1 -> 'pipe:[507536]'

, /proc , . bash, , -

$ yes 1 2  | ./find-piper.sh 
sender pid is 21380, command is "yes 1 2 "

find-piper.sh script :

#!/bin/bash

myPid=$$

# determine pipe connected to stdin:
myPipeNumber=$( readlink /proc/$myPid/fd/0 | sed -n 's,^pipe:\[\([0-9]\+\)\]$,\1,;T;p' )
if [[ -z $myPipeNumber ]] ; then
  echo "input is not a pipe"
else
  # find process with stdout connected to our pipe
  senderPipe=$( find /proc -mindepth 3 -maxdepth 3 -path "*/fd/1" -lname "pipe:\[$myPipeNumber\]" 2>/dev/null )
  senderPid=$( sed -n 's,/proc/\([0-9]\+\)/.*,\1,;T;p' <<< "$senderPipe" )

  # report pid and command line of sender
  if [[ -z $senderPid ]] ; then
    echo "could not find sender pid"
  else
    echo "sender pid is $senderPid, command is \"$( tr '\000' ' ' </proc/$senderPid/cmdline )\""
  fi
fi

# eat input
cat > /dev/null

Python :)

  • ( " " ), , , echo "Test" .
  • (, (echo "Test"; sleep 2) | python pipe.py), .
+1

All Articles