LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   My First Python script. Trying to find text manipulation (https://www.linuxquestions.org/questions/programming-9/my-first-python-script-trying-to-find-text-manipulation-4175458383/)

custangro 04-16-2013 07:31 PM

My First Python script. Trying to find text manipulation
 
So I am embarking on my first python script.

I want to

1) Take an LVM snapshot
2) Mount it RO under /mnt
3) Use "dump" to create a dumpfile to keep as backup
4) umount /mnt
5) delete the snapshot

This is what I have so far

Code:

#!/usr/bin/python
#
import os, sys, traceback
from subprocess import Popen, PIPE
#
# This is a backup script that just uses "dump"
lvcommand = ('lvs', '--noheadings')
rootvol = Popen(lvcommand, stdout=PIPE, stderr=PIPE)
print rootvol.stdout.readline()
#
##-30-

Which outputs...

Code:

[root@vr12-0801 ~]# python bakup_rhevm.py
  lv_root vg0  -wi-ao--- 268.57g

So far so good (in my book at least :P ...BUT SUGGESTIONS _are_ welcome! )

Now how do I "manipulate" this string? Because I want to take the lv_root into a variable and vg0 into another one and basically run...

Code:

lvcreate --snapshot /dev/vg0/lv_root --name lv_root_snapshot --size 15M
...but before I get ahead of myself :-)

If someone could point me to some good "text manipulation" documentation; that would be helpful :-)

OPTIONAL READING:

Some may ask "why do this in python?"

Answer: I can do this...quite easily actually in shell - but I find learning a new language is "easier" if I can actually do a "real world" problem.

Thanks!

--C

keirvt 04-16-2013 09:05 PM

python strings
 
I suggest you are in need of the split() feature
So given you have the string in a variable lvs


Code:

lvs="lv_root vg0  -wi-ao--- 268.57g"
flds=lvs.split()  # splits on whitespace
['lv_root', 'vg0', '-wi-ao---', '268.57g']
outstr="lvcreate --snapshot /dev/%s/%s --name %s_snapshot --size 15M" % (flds[1],flds[0],flds[0])
print outstr

A search engine of your choice is your friend and a search on "Python strings" should give you more of what you are after.

custangro 04-17-2013 10:05 AM

Quote:

Originally Posted by keirvt (Post 4932818)
A search engine of your choice is your friend and a search on "Python strings" should give you more of what you are after.

Perfect; exactly what I was looking for! :D


All times are GMT -5. The time now is 03:17 AM.