Issue
I have a line of Unix Shell code:
lsusb | sed -e 's/.*ID \([a-f0-9]\+:[a-f0-9]\+\).*/\1/g'
I want to pass this to the shell from a script in Python and be able to catch the output in stdout as it would be displayed in the terminal after running that line of code.
However, I cannot get it to do it. I have tried:
setting the variable I want to hold the output (x) equal to
os.system(lsusb | sed -e 's/.*ID \([a-f0-9]\+:[a-f0-9]\+\).*/\1/g')
setting
x
variable equal tosubprocess.Popen()
with all that mess being plugged in as a list and stdout being set to pipe and stderr and stdin being set toDEVNULL
setting
x
equal tosubprocess.check_output()
, again with that whole line of code being passed in.setting
x
equal to the output ofrun()
I have also tried writing lsusb
to a file and then passing that to sed
instead of piping it. I have tried passing that entire line of code and setting all that equal to a variable in the shell and then setting the variable x
equal to the shell variable. Finally, I have tried passing the output of this line of code to a file and reading the contents of that.
Everything I have tried will either give me:
just 0
these little square characters with 3 zeros and a 1 inside
nothing
How can I get the data I am wanting passed to the x
variable in a string format? This has been bugging me for a couple of days now and nothing is helping. If I need to use Python 3 that is okay, even though I prefer to use Python 2.
Thank you all for help! If you need any more information just ask and I will gladly edit them into the question here for all to see.
Thank you again!
Solution
There is a great answer about how to capture output from shell commands in Python at
Running shell command from Python and capturing the output
In this case, I suspect you need to use
subprocess.check_output("lsusb | sed -e 's/.*ID \([a-f0-9]\+:[a-f0-9]\+\).*/\1/g'", shell=True)
You need the shell=True
otherwise Python will interpret the string as a single command, rather than a pipeline.
Answered By - Jon
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.