Search code examples
pythonbashargvsys

How to get the command & arguments that was executed in shell with python


I am running a command in aws-cli to get the logs and i need to perform some opertaion in python with the output of this command.

I am doing something like this:


aws logs filter-log-events --log-group-name "something" --log-stream-names my-log-stream --filter-pattern "status=FAIL" | python3 -c "import sys, json; print(json.load(sys.stdin))" 

The above command gets the aws logs and runs the python code snippet to print the json returned.

I want to access the log-group-name and log-stream-name i.e "something" & "my-log-stream" (in this case) in my python code snippet. I am not sure how this can be done.

I have tried using sys.argv but it returns me the arguments passed in the python command i.e ['-c'] and not the aws command.


Solution

  • That is not how pipe works. It just sends the output of the command to the next command. You could set the log-group-name and log-stream-name as environment variables

    export LGN=something
    ...
    

    and then access it in python with os.environ["LGN"] ... similar to this

    export LGN="my-log-group"; <your code here> | python3 -c "import os; print(os.environ['LGN'])"