开发者

Python: open and display a text file at a specific line

开发者 https://www.devze.com 2023-01-25 11:47 出处:网络
I don\'t use Python very often, but I sometimes develop simple tools in it to make my life easier.My most frequently used is a log checker/crude debugger for SAS.It reads the SAS log line by line chec

I don't use Python very often, but I sometimes develop simple tools in it to make my life easier. My most frequently used is a log checker/crude debugger for SAS. It reads the SAS log line by line checking for any errors in my list and dumps anything it finds into standard out (I'm running Python 2.6 in a RedHat Linux environment) - along with the error, it prints the line number of that error (not that that's super useful).

What I'd really like to do is to optionally feed the script a line number and have it open the SAS log itself in GVIM and display it scrolled down to the line number I've specified. I haven't had any luck finding a way to do this - I've looked pretty thoroughly on Google to no avail. Any idea开发者_Python百科s would be greatly appreciated. Thanks! Jeremy


Once you've got the line number, you can run gvim filename -c 12 and it will go to line 12 (this is because -c <command> is "Execute <command> after loading the first file", so -c 12 is just saying run :12 after loading the file).

So I'm not sure if you really need Python at all in this case; just sending the line number direct to gvim may be all you need.


If you want line 10

>>> f = open('thefile.log')
>>> lines = f.readlines()
>>> lines[10]

Or all at once

>>> open('thefile.log').readlines()[10]

Open in gvim

>>> import subprocess
>>> subprocess.call(['gvim', '-c', '10', 'thefile.log'])


Depending on how frequently you inspect these logs and how noisy they are, it may be worth your time to put together an errorformat so you can use Vim's quickfix list to quickly jump between errors.

0

精彩评论

暂无评论...
验证码 换一张
取 消