Python equivalent to sed [solved] - 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: Python equivalent to sed [solved] (/thread-13025.html) |
Python equivalent to sed [solved] - cygnus_X1 - Sep-24-2018 I'm trying to create a program guide for BBC Radio 4 Extra. I'm using python3.4 and Debian linux on Raspberry Pi In linux the stream editor (sed) can extract content using sed -n '/14:00/, +3p' mon which will extract from program guide (mon) at time 14:00 and display next 3 lines +3p In python3 I've redirected stdout to a variable called 'content' which works but cannot find a way to make the time a variable. Code used insert os content = os.popen("sed -n '/14:00/, +3p' mon").read()This gives the same results and content gets the value of stdout. However if I wanted to change time (14:00) I cannot pass this as a variable e.g. time ="14:00" content = os.popen("sed -n '/time/, +3p' mon").read() fails to extract any content. There is possibly more than one way to do this, and there may be some function in the python standard library. I can't find a way to attach the file called 'mon' Truncated content below: Thanks in advance.
RE: Python equivalent to sed - nilamo - Sep-24-2018 (Sep-24-2018, 02:32 PM)cygnus_X1 Wrote: time ="14:00" It would be a crazy world indeed, if all your variables were just injected into strings. You need to specifically let python know in some way that you expect interpolation to be taking place: >>> time = "14:00" >>> "spam /time/ eggs" 'spam /time/ eggs' >>> "spam /{0}/ eggs".format(time) 'spam /14:00/ eggs' >>> f"spam /{time}/ eggs" 'spam /14:00/ eggs' RE: Python equivalent to sed [solved] - cygnus_X1 - Sep-24-2018 Thanks for your reply Nilamo, I see my mistake now. content = os.popen("sed -n '/time/, +3p' mon").read() The solution I used was string concatenation: str1 = "sed -n '/" + str(time)+ "/, +3p' mon" content = os.popen(str1).read()It may not be the best or indeed the only solution but it works for my purpose. |