Reputation: 363
I am trying to remove the comments when printing this list.
I am using
output = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
for item in output:
print item
This is perfect for giving me the entire file, but how would I remove the comments when printing?
I have to use cat for getting the file due to where it is located.
Upvotes: 2
Views: 168
Reputation: 26329
The function self.cluster.execCmdVerify
obviously returns an iterable
, so you can simply do this:
import re
def remove_comments(line):
"""Return empty string if line begins with #."""
return re.sub(re.compile("#.*?\n" ) ,"" ,line)
return line
data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
for line in data:
print remove_comments(line)
The following example is for a string output:
To be flexible, you can create a file-like object from the a string (as far as it is a string)
from cStringIO import StringIO
import re
def remove_comments(line):
"""Return empty string if line begins with #."""
return re.sub(re.compile("#.*?\n" ) ,"" ,line)
return line
data = self.cluster.execCmdVerify('cat /opt/tpd/node_test/unit_test_list')
data_file = StringIO(data)
while True:
line = data_file.read()
print remove_comments(line)
if len(line) == 0:
break
Or just use remove_comments()
in your for-loop
.
Upvotes: 2
Reputation: 584
If it's for a python file for example and you want to remove lines beginning with # you can try :
cat yourfile | grep -v '#'
EDIT:
if you don't need cat, you can directly do :
grep -v "#" yourfile
Upvotes: 0
Reputation: 20039
What about greping the output
grep -v '#' /opt/tpd/node_test/unit_test_list
Upvotes: 0
Reputation: 43265
You can use regex re
module to identify comments and then remove them or ignore them in your script.
Upvotes: 2