Sunday, April 27, 2014

Deep first search - unrecursion

def deep_first_search(vpath):
root = Node(vpath)
node = root
while True:
objs = list_directory(node.name)
for obj in objs:
child = Node(node.name + obj['objname'] + '/', node)
node.set_child(child)
first_child = node.first_child
if first_child:
node = first_child
else:
while not node.has_next_sibling:
if node is root:
break
if node is root:
first_child = node.first_child
if first_child:
node = first_child
continue
else:
break
tmp = node
node = node.next_sibling(node)
node.remove_sibling(tmp)

class Node(object):
"""docstring for Node"""
def __init__(self, name, parent=None):
super(Node, self).__init__()
self.__name = name
self.__parent = parent
self.__child_nodes = []

@property
def has_next_sibling(self):
try:
if self.__parent != None:
return len(self.__parent.__child_nodes) > 1
else:
return False
except (IndexError, AttributeError):
return False

@property
def name(self):
return self.__name

@property
def parent(self):
return self.__parent

@property
def first_child(self):
try:
return self.__child_nodes[0]
except (IndexError, AttributeError):
return None

def next_sibling(self, node):
try:
if self.__parent != None:
i = self.__parent.__child_nodes.index(node)
return self.__parent.__child_nodes[i+1]
else:
return None
except (IndexError, AttributeError):
return None

def set_child(self, node):
self.__child_nodes.append(node)

def remove_child(self, node):
try:
self.__child_nodes.remove(node)
except Exception, e:
raise e

def remove_sibling(self, node):
try:
self.__parent.__child_nodes.remove(node)
except Exception, e:
raise e

Saturday, April 19, 2014

All file modes in Python


  • r for reading
  • w for writing
  • r+ opens for reading and writing (cannot truncate a file)
  • w+ for writing and reading (can truncate a file)
  • rb+ reading or writing a binary file
  • wb+ writing a binary file
  • a+ opens for appending

Monday, April 14, 2014

run command with another user on debian


su -c "command here" -s /bin/sh another_user_here
example:
#su -c "cat /etc/groups" -s /bin/sh www-data

Friday, April 4, 2014

get all files or subdirectories in directory

cách 1:
>> liệt kê file và directory
#ls -l | awk '{print $9}'
>> liệt kê cả file ẩn
#ls -la | awk '{print $9}'
>> nếu chỉ muốn liệt kê directory
#ls -l | grep ^d | awk '{print $9}' 
>> nếu chỉ muốn liệt kê file
#ls -l | grep -v ^d | awk '{print $9}' 

cách 2:
#find . -maxdepth 1 -type f
>> xem kết quả
./.DS_Store
./03.mp3
./13ductinh.txt
./EsuDotNet_2.1.4.31.zip
./get_test.txt

./test
#str_to_rep=""
#for item in `find . -maxdepth 1 -type f`; do
#filename="${filename//.\//str_to_rep}"
#echo $filename
#done
>> kết quả
.DS_Store
03.mp3
13ductinh.txt
EsuDotNet_2.1.4.31.zip
get_test.txt
test
>> nếu không muốn hiển thị file ẩn
#find . -not -path '*/\.*' -maxdepth 1 -type f