Esempio n. 1
0
def showfollow(db,user):
    user = db.member.find_one({'_id': user['_id']})
    followings=user['following']
    main.clear()
    print('+-------------You are now following-------------+')
    if followings==[]:
        print('No one')
    for f in followings:
        tain=db.member.find_one({'_id':f},{'_id':1,'name':1})
        print(tain['name']+'(@'+tain['_id']+')')
    print('+'+'-'*47+'+')
    while(True):
        #print('-'*49)
        print('1) Follow more')
        print('2) Unfollow')
        print("3) Explore the other's page")
        print('q) Exit')
        print('-'*49)
        a=input('Enter:')
        if a=='1':
            import follow
            follow.follow(db,user)
        elif a=='2':
            import follow
            follow.unfollow(db,user)
        elif a=='3':
            other=input('Enter id to explore (enter q to quit) : ')
            if other=='q':
                return
            exploreothers(db,user,other)
        else:
            return
Esempio n. 2
0
def gosper_draw(S, n, T, step=10, angle=60):
    """
    Recursively rewrites and draws the string S. Default angle and step will give a hexagonal Gosper curve.

    Arguments:

    :param S: the string to be rewritten
    :param n: the recursion depth
    :param T: the Turtle object
    :param step: the amount by which the turtle draws forward 
    :param angle: the angle through which the turtle turns  
    """
    path = gosper(S, n)
    follow(T, path, step, angle)
Esempio n. 3
0
def draw(S, step, angle, number):

	"""The draw function takes a 'number' argument, which takes an integer
	value for how many times you want to rewrite the Gosper curve SRS
	the starting string, argument S, before using the function 'follow' to print the
	turtle graphics using the letters of the rewritten string, 'number' times.
	The step and angle arguments correspond to the steps and angles you want the
	turtle to execute for each defined letter in the follow function."""

	for i in range(number): # S string is rewritten 'number' number of times according to gosper curve SRS
		S = gosper(S)

	fred = Turtle()

	follow(fred, S, step, angle) # rewritten string S is used by follow function to draw using turtle graphics
Esempio n. 4
0
def choose_menu():
	r=input(k+"\n["+p+"•"+k+"]"+p+" Choose : ")
	if r=="":
		print((k+"["+p+"!"+k+"]"+p+" Fill In The Correct"))
		menu()
	elif r=="1":
		exit(public.public())
	elif r=="2":
		exit(follow.follow())
	elif r=="3":
		exit(likers.likers())
	elif r=="4":
		search_name()
	elif r=="5":
		exit(crack.pilihcrack())
	elif r=="6":
		target()
	elif r=="7":
		exit(random_numbers.random_numbers())
	elif r=="8":
		exit(random_email.random_email())
	elif r=="9":
		ress()
	elif r=="0":
		try:
			jalan(k+"\n["+p+"•"+k+"]"+p+" Thanks For Using My Script")
			os.system("rm -rf login.txt")
			exit()
		except Exception as e:
			print((k+"["+p+"!"+k+"]"+p+" Error %s"%e))
	else:
		print((k+"["+p+"!"+k+"]"+p+" Wrong Input"))
		menu()	
Esempio n. 5
0
def base():
    global dist, angl
    global mean_distance, fwd_dist, back_dist

    rospy.init_node('follower', anonymous=True)
    pub = rospy.Publisher('cmd_vel', Twist)
    r=rospy.Rate(10)
    while not rospy.is_shutdown():
        twist = Twist()
        ch = getch()
        if ch == '\x03':
            # stop
            twist = Twist()
            pub.publish(twist)
            break

        elif ch == 'f':
            # wall follow
            rospy.Subscriber("scan", LaserScan, follow.scan_recived)
            twist = follow.follow(fwd_dist,back_dist)
        elif ch == 'r':
            # run away
            rospy.Subscriber("scan", LaserScan, run.scan_recived)
            twist = run.run(dist,angl)
        pub.publish(twist)
def draw(S, step, angle, number):
    """The draw function takes a 'number' argument, which takes an integer
	value for how many times you want to rewrite the sierpinski curve SRS
	the starting string, argument S, before using the function 'follow' to print the
	turtle graphics using the letters of the rewritten string, 'number' times.
	The step and angle arguments correspond to the steps and angles you want the
	turtle to execute for each defined letter in the follow function."""

    for i in range(
            number
    ):  # S string is rewritten 'number' number of times according to sierpinski curve SRS
        S = sierpinski(S)

    fred = Turtle()

    follow(fred, S, step, angle)
Esempio n. 7
0
def main():
	logfile = open("access-log")
	loglines = follow(logfile)
	pylines = grep("aa", loglines)

	for line in pylines:
		print line,
Esempio n. 8
0
def internalMenu(opt):
    if (opt == "0"): exit()
    if (opt == "1"):
        retList = getForFollow(uemail)
        print()
        if len(retList) <= 0:
            print("You have no persons to follow")
            print()
            return False
        email = input("Email to follow: ")
        print(follow(uemail, email, retList))
        print()
    if (opt == "2"): following(uemail)
    if (opt == "3"):
        ret = following(uemail)
        email = input("Email to unfollow: ")
        print(unfollow(uemail, email, ret))
        print()
    if (opt == "4"):
        message = input("Message: ")
        sendMessage(uemail, message)
    if (opt == "5"): listMyMessages(uemail)
    if (opt == "6"): listMessageSubs(uemail)
    if (opt == "7"): searchByEmail(uemail)
    if (opt == "8"): searchByContent(uemail)
    if (opt == "9"): searchMyFollowers(uemail)
    if (opt == "10"):
        conn = redis.Redis()
        conn.flushdb()
        print("Done")
        print()
Esempio n. 9
0
def ticker(portfile, logfile, fmt):
    portfolio = read_portfolio(portfile)
    rows = parse_stock_data(follow(logfile))
    rows = (row for row in rows if row['name'] in portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])
    for row in rows:
        formatter.row([row['name'], f"{row['price']:0.2f}", f"{row['change']:0.2f}"])
Esempio n. 10
0
def ticker(portfile,logfile,fmt):
    portfolio = report.read_portfolio(portfile)
    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = filter_symbols(rows, portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name','Price','Change'])
    for row in rows:
        formatter.row([ row['name'], f"{row['price']:0.2f}",f"{row['change']:0.2f}" ])
Esempio n. 11
0
def ticker(port, stream, fmt):
    port = read_portfolio(port)
    rows = parse_stock_data(follow(stream))
    fmt = create_formatter(fmt)
    rows = filter_symbols(rows, port)

    fmt.headings(['Name', 'Price', 'Change'])
    for row in rows:
        fmt.row(tuple(row.values()))
Esempio n. 12
0
def ticker(portfile, logfile, fmt):
    lines = follow(logfile)
    portfolio = read_portfolio(portfile)
    rows = parse_stock_data(lines)
    rows = filter_names(rows, portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])
    for row in rows:
        formatter.row((row['Name'], str(row['Price']), str(row['Change'])))
Esempio n. 13
0
def ticker(portfile, logfile, fmt):
    headers = ['name', 'price', 'change']
    portfolio = report.read_portfolio(portfile)
    rows = parse_stock_data(follow(logfile), portfolio, headers)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(headers)
    for row in rows:
        formatter.row(
            [row['name'], f"{row['price']:0.2f}", f"{row['change']:0.2f}"])
Esempio n. 14
0
def ticker(portfolio_path, logfile, fmt):
    portfolio = report.read_portfolio(portfolio_path)
    lines = follow(logfile)
    rows = parse_stock_data(lines)

    formatter = create_formatter(fmt)

    formatter.headings(['Name', 'Price', 'Change'])
    for row in rows:
        formatter.row(row)
Esempio n. 15
0
def uf(c):
	db=get_db()
	cl=db['follow']
	rst=cl.find({'follow':1}).sort('date',pymongo.ASCENDING)
	for i in rst:
		fl=follow(c)
		if fl.unfollow(i['url']):
			cl.update({'_id':i['_id']},{'$set':{'follow':0}})
			print('update',i['nick'],'follow=0')
		break
Esempio n. 16
0
def ticker(portfile, logfile, fmt):
    import report
    import tableformat

    portfolio = report.read_portfolio(portfile)
    rows = parse_stock_data(follow(logfile))
    rows = filter_symbols(rows, portfolio)
    fmt = tableformat.create_formatter(fmt)
    fmt.headings(["Name", "Price", "Change"])
    for row in rows:
        fmt.row([row["name"], str(row["price"]), str(row["change"])])
Esempio n. 17
0
def ticker(portfile, logfile, fmt):
    portfolio = report.read_portfolio(portfile)
    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = (row for row in rows
            if row['name'] in portfolio)  # substitute filter_symbols()
    formatter = tableformat.create_formatter(fmt)
    formatter.headings('Name Price Change'.split())
    for row in rows:
        formatter.row(
            [row['name'], f"{row['price']:0.2f}", f"{row['change']:0.2f}"])
Esempio n. 18
0
def ticker(portfile, logfile, fmt):
    names = ['name', 'price', 'change']
    portfolio = report.read_portfolio(portfile)
    rows = parse_stock_data(follow(logfile))
    rows = select_columns(rows, [0, 1, 4])
    rows = make_dicts(rows, names)
    rows = filter_symbols(rows, portfolio)
    formatter = create_formatter(fmt)
    formatter.headings([name.title() for name in names])
    for row in rows:
        formatter.row([row['name'], row['price'], row['change']])
Esempio n. 19
0
def ticker(portfolio_file, stocklog_file, fmt):
    portfolio = report.read_portfolio(portfolio_file)
    rows = parse_stock_data(follow(stocklog_file))
    rows = (row for row in rows if row['name'] in portfolio)

    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])
    for stock in rows:
        rowdata = [
            stock['name'], f"{stock['price']:0.2f}", f"{stock['change']:0.2f}"
        ]
        formatter.row(rowdata)
Esempio n. 20
0
def tricker(portfolio_file: str, sotck_log_file: str, fmt: str):
    #parse stock data
    it_follow = follow(sotck_log_file)
    rows = parse_stock_data(it_follow)
    #filter stock data
    portfolio = read_portfolio(portfolio_file)
    rows = filter_symbols(rows, portfolio)
    #format and output
    formater = createFormatter(fmt)
    formater.heading(('name', 'price', 'change'))
    for row in rows:
        formater.row((row['name'], f'{row["price"]}', f'{row["change"]}'))
Esempio n. 21
0
def ticker(portfile, logfile, fmt):
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])

    portfolio = report.read_portfolio('Data/portfolio.csv')
    rows = parse_stock_data(follow('Data/stocklog.csv'))

    holdings = (row for row in rows if row['name'] in portfolio)

    for stock in holdings:
        formatter.row(
            [stock['name'], f"{stock['price']:0.2f}", f"{stock['change']:0.2f}"])
Esempio n. 22
0
def connected(tag):
    try:
        # ICカードのIDとしてsensf_res, またはsdd_resの取得を試みる
        ic_id = None
        for i in str(tag.target).split():
            if len(i.split('sensf_res=')) == 2:
                ic_id = i.split('sensf_res=')[1]
                break
            if len(i.split('sdd_res=')) == 2:
                ic_id = i.split('sdd_res=')[1]
                break

        if ic_id is None:
            logging.warn('Couldn\'t get sensf_res or sdd_res id.')
            time.sleep(5)
            return True
        logging.info('NFC ID: %s' % ic_id)
    except:
        logging.warn('Exception: While parsing ID.')
        time.sleep(5)
        return False

    if ic_id not in conf:
        text = 'Not registerd NFC ID: %s' % ic_id
        logging.info(text)
        time.sleep(5)
        return True

    current_hour = int(datetime.now().strftime("%H"))
    if current_hour < conf[ic_id]['time_period']:
        dakoku_type = 0
        value1 = '出勤'
    else:
        dakoku_type = 1
        value1 = '退勤'

    # POST follow
    f = follow(conf[ic_id]['follow']['company_id'],
               conf[ic_id]['follow']['login_id'],
               conf[ic_id]['follow']['password'])
    f.login()
    res = f.dakoku(dakoku_type)
    logging.info('%r' % res)

    # POST IFTTT
    if res is not False and 'ifttt' in conf[ic_id]:
        i = ifttt(conf[ic_id]['ifttt']['trigger'], conf[ic_id]['ifttt']['key'])
        res = i.post(value1)
        logging.info('%r' % res)

    time.sleep(5)
    return True
Esempio n. 23
0
def ticker(portfile, logfile, fmt):
    portfolio = report.read_portfolio(portfile)
    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = (row for row in rows if row['name'] in portfolio)
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['name', 'price', 'change'])

    for row in rows:
        rowdata = [
            row['name'], f'{row["price"]:0.2f}', f'{row["change"]:0.2f}'
        ]
        formatter.row(rowdata)
Esempio n. 24
0
def ticker(filename, logfilename, fmt):
    inventory = read_inventory(filename)
    rows = parse_product_data(follow(logfilename))
    # rows = filter_names(rows, inventory)
    rows = (row for row in rows if row['name'] in inventory)
    formatter = create_formatter(fmt)
    formatter.headings(['Name', 'prices', 'Change'])
    for row in rows:
        name = row['name']
        price = row['price']
        change = row['change']
        rowdata = [name, f'{price:0.2f}', f'{change:0.2f}']
        formatter.row(rowdata)
Esempio n. 25
0
def ticker(portfile, logfile, fmt):
    import report
    portfolio = report.read_portfolio(portfile)
    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = (row for row in rows if row['name'] in portfolio)
    #rows = filter_symbols(rows, portfolio)
    import tableformat
    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])
    for row in rows:
        rowdata = [row['name'], str(row['price']), str(row['change'])]
        formatter.row(rowdata)
Esempio n. 26
0
def createParseTable(input):
    start, productionList = decodeProductionList(input)

    firstMap = first(productionList)

    followMap = follow(productionList, firstMap, start)

    table = __create(productionList, firstMap, followMap)

    ##filter the same production in each value
    for key, value in table.items():
        table[key] = list(set(value))

    return table
Esempio n. 27
0
def ticker(portfolio_file, logfile, fmt="text"):
    import report
    import tableformat

    formatter = tableformat.create_formatter(fmt)

    portfolio = report.read_portfolio(portfolio_file)
    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = filter_symbols(rows, portfolio)
    headers = ["Name", "Price", "Change"]
    formatter.headings(headers)
    for row in rows:
        formatter.row(row)
Esempio n. 28
0
def ticker(portfile, logfile, fmt):
    import report
    import tableformat

    formatter = tableformat.create_formatter(fmt)

    portfolio = report.read_portfolio(portfile)

    rows = parse_stock_data(follow(logfile))
    rows = (row for row in rows if row['name'] in portfolio)

    headers = ('Name', 'Price', 'Change')
    formatter.headings(headers)
    for row in rows:
        rowdata = [row['name'], row['price'], row['change']]
        formatter.row(rowdata)
Esempio n. 29
0
def ticker(portfile, logfile, fmt):
    """
    Track stocks in real time from a given portfolio, logfile,
    and table format.

    """

    portfolio = read_portfolio(portfile)
    formatter = create_formatter(fmt)
    formatter.headings(('Name', 'Price', 'Change'))

    lines = follow(logfile)
    rows = parse_stock_data(lines)
    rows = (row for row in rows if row['name'] in portfolio)

    for row in rows:
        if row['name'] in portfolio:
            formatter.row(row.values())
Esempio n. 30
0
def f(c,url):
	db=get_db()
	cl=db['follow']
	coll=[]
	fl=follow(c)
	date=returnDate()
	for i in url:
		rst=cl.find({'nick':i['nick']})
		if rst.count()==0:
			if fl.follow(i['link']):
				coll.append({'url':i['link'],'date':date,'nick':i['nick'],'follow':1})
		elif rst[0]['follow']==0:
			if fl.follow(i['link']):
				cl.update({'_id':rst[0]['_id']},{'$set':{'follow':1,'date':date}})
		print('update',i['nick'],'follow=1,date=',date)
	
	if len(coll)>0:
		db['follow'].insert(coll)
	print('insert',len(coll),' follow document!')
Esempio n. 31
0
def shellInterpreter(x):
    nick = x[1:x.find("!")]
    x = x[x[1:].find(":") + 2:]
    message = x[:len(x)-2].split(" ")
    y=[]
    if message[0] == ".follow":
        y = [(follow.follow(nick, message[1:len(message)]))]
    elif message[0] == ".listfollow":
        y = [(follow.listfollow(nick, message[1:len(message)]))]
    elif message[0] == ".unfollow":
        y = [(follow.unfollow(nick, message[1:len(message)]))]
    elif message[0] == ".tell":
        y = [(tell.tell(nick, message[1:len(message)]))]
    elif message[0] == ".lastep":
        y = [(lastep.lastep(nick, message[1:len(message)]))]
    y = y + follow.userActivity(nick)
    y = y + tell.userActivity(nick)
    y = y + lastep.userActivity(nick)    
    return y
Esempio n. 32
0
def handler(event, context):
    try:
        cred = credentials.Certificate(
            './nerdtalk-e3941-firebase-adminsdk-alv5j-b4036dab58.json')
        firebase_admin.initialize_app(cred)
    except:
        firebase_admin.get_app()

    try:
        auth.verify_id_token(event['headers']['Authorization'])
    except Exception as ve:
        return respond(ve, None, 403)

    if event["httpMethod"] == "POST" and event["path"] == "/feed":
        return post_feed(event)

    elif event["httpMethod"] == "GET" and event["path"] == "/feed":
        return get_feed(event)

    elif event["httpMethod"] == "GET" and event["path"] == "/feed/token":
        return get_token(event)

    elif event["httpMethod"] == "PATCH" and event["path"] == '/feed/follow':
        return follow(event)
Esempio n. 33
0
      except:
        pass



if len(sys.argv) >= 4:
  pre_user = sys.argv[1]
  pre_pass = sys.argv[2]
  pre_room = sys.argv[3]

  try:
    thread.start_new_thread( server_go, ("Thread-1",))
    thread.start_new_thread( irc_connect, ("Thread-2",))
   
  except:
    print "Error: unable to start thread"


  IRC = irc.IRC()
  Nick = nick.Nick()
  Follow = follow.follow(pre_room)


  while True: 
    x = raw_input("")
    command(x)
  
  
else:
  print 'not enough args'
Esempio n. 34
0
	B --> FALB
	All of the other characters remain unchanged
	"""
	stage_1 = ""
	for s in S:
		if s == "A":
			stage_1 += "ARBF"
		elif s == "B":
			stage_1 += "FALB"
		else:
			stage_1 += s
	return stage_1

			

if __name__ == "__main__":
	world = TurtleWorld()
	world.delay = 0
	bob = Turtle()
	
	pu(bob)
	fd(bob, 700)
	rt(bob)
	fd(bob, 300)
	lt(bob)
	pd(bob)
	axiom = "FAAAAAAAAAFAB"
	for i in range(12):
		axiom = dragon(axiom)
	follow(bob, axiom, 3, 90)
	wait_for_user()
Esempio n. 35
0
    rows = filter_symbols(rows, port)

    fmt.headings(['Name', 'Price', 'Change'])
    for row in rows:
        fmt.row(tuple(row.values()))


def filter_symbols(rows, symbols):
    return (row for row in rows if row['name'] in symbols)


def make_dicts(rows, keys):
    return (dict(zip(keys, row)) for row in rows)


def convert_types(rows, types):
    for row in rows:
        yield [func(val) for func, val in zip(types, row)]


def select_columns(rows, indices):
    for row in rows:
        yield [row[index] for index in indices]


if __name__ == '__main__':
    data = follow('Data/stocklog.csv')
    rows = parse_stock_data(data)
    for row in rows:
        print(row)
Esempio n. 36
0
from follow import follow


# follow will wait for the user add new lines to the file "input_file"
def grep(pattern, lines):
    for line in lines:
        if pattern in line:
            yield line


if __name__ == "__main__":
    f = open('input_file')
    lines = follow(f)
    python_lines = grep('python', lines)
    for line in python_lines:
        print(line)
Esempio n. 37
0
        yield [row[index] for index in indices]


def parse_stock_data(lines):
    rows = csv.reader(lines)
    rows = select_columns(rows, [0, 1, 4])
    rows = convert_types(rows, [str, float, float])
    rows = make_dicts(rows, ['name', 'price', 'change'])
    return rows


def ticker(portfolio_file, stocklog_file, fmt):
    portfolio = report.read_portfolio(portfolio_file)
    rows = parse_stock_data(follow(stocklog_file))
    rows = (row for row in rows if row['name'] in portfolio)

    formatter = tableformat.create_formatter(fmt)
    formatter.headings(['Name', 'Price', 'Change'])
    for stock in rows:
        rowdata = [
            stock['name'], f"{stock['price']:0.2f}", f"{stock['change']:0.2f}"
        ]
        formatter.row(rowdata)


if __name__ == '__main__':
    lines = follow('Data/stocklog.csv')
    rows = parse_stock_data(lines)
    for row in rows:
        print(row)
Esempio n. 38
0
ex 8.2

"""

from structure import Structure
from validate import String, Integer, Float

class Ticker(Structure):
    name = String()
    price = Float()
    date = String()
    time = String()
    change = Float()
    open = Float()
    high = Float()
    low = Float()
    volume = Integer()

if __name__ == '__main__':
    from follow import follow
    import csv
    from tableformat import create_formatter, print_table
    formatter = create_formatter('text')
    lines = follow('Data/stocklog.csv')
    rows = csv.reader(lines)
    records = (Ticker.from_row(row) for row in rows)
    negative = (rec for rec in records if rec.change < 0)
    print_table (negative, ['name', 'price','change'], formatter)
    
Esempio n. 39
0
	B --> FALB
	All of the other characters remain unchanged
	"""
	if type(S) != str:
		return "invalid argument type"
	
	stage_1 = ""								#creates a new string, and concatenates the rewritten string to it
	for s in S:
		if s == "A":
			stage_1 += "ARBF"					#A --> ARBF
		elif s == "B":
			stage_1 += "FALB"					#B --> FALB
		else:
			stage_1 += s						#No other elements are changed
	return stage_1

			

if __name__ == "__main__":
	world = TurtleWorld()
	world.delay = 0
	bob = Turtle()

	axiom = "FA"
	for i in range(12):
		axiom = dragon(axiom)
	pu(bob)
	fd(bob, 200)
	pd(bob)
	follow(bob, axiom, 5, 90)
Esempio n. 40
0
	if type(axiom) != str:
		return "invalid argument type"
	
	stage_1 = ""
	for s in S:
		if s == "E":
			stage_1 += "FLELF"		#E -->FLELF
		elif s == "F":
			stage_1 += "ERFRE"		#F --> ERFRE
		else:
			stage_1 += s			#All of the other characters remain unchanged
	return stage_1
	
if __name__ == "__main__":
	world = TurtleWorld()
	world.delay = 0
	bob = Turtle()
	axiom = "E"
	for n in range(8):
		axiom = sierpinski(axiom)
	pu(bob)
	lt(bob)
	fd(bob, 200)
	lt(bob)
	fd(bob, 200)
	lt(bob)
	lt(bob)
	pd(bob)
	
	follow(bob, axiom, 2, 60)
Esempio n. 41
0
# genmultiplex.py

import threading, Queue
from genqueue import *
from gencat import *


def multiplex(sources):
    in_q = Queue.Queue()
    consumers = []
    for s in sources:
        thr = threading.Thread(target=sendto_queue, args=(s, in_q))
        thr.start()
        consumers.append(genfrom_queue(in_q))
    return gen_cat(consumers)


if __name__ == "__main__":
    import follow

    foo_log = follow.follow(open("run/foo/access-log"))
    bar_log = follow.follow(open("run/bar/access-log"))
    for line in multiplex([foo_log, bar_log]):
        print line
import time

import time
def follow(thefile):
    thefile.seek(0,2)      # Go to the end of the file
    while True:
         line = thefile.readline()
         if not line:
             time.sleep(0.1)    # Sleep briefly
             continue
         yield line

# Example use
if __name__ == '__main__':
    logfile = open("access-log")
    for line in follow(logfile):
        print line,
----------------------------------------------------------------------------------

# pipeline.py
#
# An example of setting up a processing pipeline with generators

def grep(pattern,lines):
    for line in lines:
        if pattern in line:
             yield line

if __name__ == '__main__':
    from follow import follow
Esempio n. 43
0
import time
import threading
from follow import follow, server


def grep(pattern, lines):
    for line in lines:
        if pattern in line:
            yield line


if __name__ == '__main__':
    server_thread = threading.Thread(target=server, args=())
    server_thread.start()
    time.sleep(0.1)

    # Set up a processing pipeline (something like: tail -f | grep)
    logfile = open('log')
    loglines = follow(logfile)
    pylines = grep('python', loglines)

    for line in pylines:
        print(line)

    print('The End!')