Gribouillis 1,391 Programming Explorer Team Colleague

Once you saved the file quantile.py in the same directory, if you want to use the quantile function in program.py, you have to put

from quantile import quantile

before you use quantile in program.py (typically at the top of the program).

Gribouillis 1,391 Programming Explorer Team Colleague

Why can't I use tabs ? I hate it when I every time have to hit 4 times the tab.
Btw every program I made till now works with those tabs.

Your favorite editor DOES have a configuration option to write 4 spaces instead of a tab !

Gribouillis 1,391 Programming Explorer Team Colleague

Also, all this should be written using module bisect:

from bisect import bisect
limits = [100, 1000, 2500, 5000, 10000, 25000, 50000, 100000]
pairs = [
    (5, 70), (50, 700), (100, 1000), (250, 2000),
    (500, 5000), (1000, 7500), (2500, 10000), (5000, 10000),
    (1, 1000000000)
]

a, b = pairs[bisect(limits, saldo)]
Gribouillis 1,391 Programming Explorer Team Colleague

Replace line 5 with money = int(f.readline().strip()) .

Gribouillis 1,391 Programming Explorer Team Colleague

The tread must also be created by

thread1 = threading.Thread(target = stringFunction, arg = ("one", my_queue))

and not threading.Thread(stringFunction("one", my_queue)).

Gribouillis 1,391 Programming Explorer Team Colleague

You can use a code structure like this:

next_number = 52
for i, line in enumerate(fin):
    if i == next_number:
        fout.write(line)
        next_number += 102
Gribouillis 1,391 Programming Explorer Team Colleague

The python 2.6 documentation says that the first argument None in str.translate is new in 2.6. Previously, the first argument had to be a string of 256 characters (translation table). I suppose you should write something like

import sys
if sys.version_info < (2, 6):
    table = ''.join(chr(i) for i in xrange(256))
else:
    table = None

k.translate(table,':.-')
Gribouillis 1,391 Programming Explorer Team Colleague

Hello... I have problem with regex, I want to get the tables from another site... the regex is re.compile(r'<table.*?>(.*?)</table>') but when I get the tables I don't know how to return the value into the tables.

#html = the page
tbl = re.compile(r'<table.*?>(.*?)</table>')
return tbl.sub('', html) #return html without <table>...</table>
# how to return the value only of <table> tags... without the other tags ?

Thanks.

I suggest

the_list = tbl.findall(html)

There is also finditer which returns a sequence of match objects.

Gribouillis 1,391 Programming Explorer Team Colleague

Assuming the name of your service is service , you could try to run this program

# runservice.py
import subprocess as sp
import sys
SERVICE_COMMAND = "service"

def run_service(command):
    with open("output.txt", "w") as output_file:
        process = sp.Popen(command, shell=True, stdout=sp.PIPE)
        for line in process.stdout:
            for f in (output_file, sys.stdout):
                f.write(line)
        process.wait()

if __name__ == "__main__":
   run_service(SERVICE_COMMAND)
Gribouillis 1,391 Programming Explorer Team Colleague

You could put this in __init__.py

# __init__.py
def _load():
    from glob import glob
    from os.path import join, dirname, splitext, basename

    for path in glob(join(dirname(__file__),'[!_]*.py')):
        name = splitext(basename(path))[0]
        exec "from %s import *" % name in globals()
_load()

Note that all the submodules will be loaded when you load subs. Also you should put a __all__ variable in your submodules to import only the names you need. For example

# file1.py
__all__ = ["useful_function",] # list of functions to export

def useful_function():
    pass

def helper_function(): # not in __all__ --> not exported
    pass

Also, a simpler solution is to write

# app.py
from subs.file1 import func1
func1()

With the above code, you can write

# app.py
from subs import func1
func1()
Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you should call matplotlib.pyplot.show() after imshow.

Gribouillis 1,391 Programming Explorer Team Colleague

Looking into pyton 2.6 source code (timemodule.c) we find this implementation of sleep

/* Implement floatsleep() for various platforms.
   When interrupted (or when another error occurs), return -1 and
   set an exception; else return 0. */

static int
floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
	struct timeval t;
	double frac;
	frac = fmod(secs, 1.0);
	secs = floor(secs);
	t.tv_sec = (long)secs;
	t.tv_usec = (long)(frac*1000000.0);
	Py_BEGIN_ALLOW_THREADS
	if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
#ifdef EINTR
		if (errno != EINTR) {
#else
		if (1) {
#endif
			Py_BLOCK_THREADS
			PyErr_SetFromErrno(PyExc_IOError);
			return -1;
		}
	}
	Py_END_ALLOW_THREADS
#elif defined(__WATCOMC__) && !defined(__QNX__)
	/* XXX Can't interrupt this sleep */
	Py_BEGIN_ALLOW_THREADS
	delay((int)(secs * 1000 + 0.5));  /* delay() uses milliseconds */
	Py_END_ALLOW_THREADS
#elif defined(MS_WINDOWS)
	{
		double millisecs = secs * 1000.0;
		unsigned long ul_millis;

		if (millisecs > (double)ULONG_MAX) {
			PyErr_SetString(PyExc_OverflowError,
					"sleep length is too large");
			return -1;
		}
		Py_BEGIN_ALLOW_THREADS
		/* Allow sleep(0) to maintain win32 semantics, and as decreed
		 * by Guido, only the main thread can be interrupted.
		 */
		ul_millis = (unsigned long)millisecs;
		if (ul_millis == 0 ||
		    main_thread != PyThread_get_thread_ident())
			Sleep(ul_millis);
		else {
			DWORD rc;
			ResetEvent(hInterruptEvent);
			rc = WaitForSingleObject(hInterruptEvent, ul_millis);
			if (rc == WAIT_OBJECT_0) {
				/* Yield to make sure real Python signal
				 * handler called.
				 */
				Sleep(1);
				Py_BLOCK_THREADS
				errno = EINTR;
				PyErr_SetFromErrno(PyExc_IOError);
				return -1;
			}
		}
		Py_END_ALLOW_THREADS
	}
#elif defined(PYOS_OS2)
	/* This Sleep *IS* Interruptable by Exceptions */
	Py_BEGIN_ALLOW_THREADS
	if (DosSleep(secs * 1000) != NO_ERROR) {
		Py_BLOCK_THREADS
		PyErr_SetFromErrno(PyExc_IOError);
		return -1; …
Gribouillis 1,391 Programming Explorer Team Colleague

Thanks... that's what I needed. However, I'd like to know HOW a timer is created in python.

Apart from the sleep function, there is a Timer class in the threading module and there are timers in gui modules like tkinter and wxpython. Other ways to wait are the threading.Condition.wait() function, socket reading with a timeout and functions like select.select which wait for I/O with an optional timeout.
Your choice depends on what you want to do exactly.

Gribouillis 1,391 Programming Explorer Team Colleague

You should be able to do this by invoking a shell command, which depends on your linux distribution, to list the packages installed on your computer. This command should look like rmp -qa | grep unrar on some distributions or dpkg -list unrar on other distributions and perhaps another command on your distribution. Check which command applies to your distro.
Once you have the shell command, you can use the subprocess module to run the command and check it's output, like this

import subprocess as sp
command = "rpm -qa | grep unrar"
child = sp.Popen(command, shell = True, stdout = sp.PIPE, stderr = sp.PIPE)
output, error = child.communicate()
if child.returncode:
    # command failed
    raise RuntimeError(error)
else:
    # Success. The string 'output' contains your command's output
    draw_conclusions_from_command_output(output)
Gribouillis 1,391 Programming Explorer Team Colleague

If you have problems with reusing the same port, you should try this socket option

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

just after creating the socket with socket.socket().

Gribouillis 1,391 Programming Explorer Team Colleague

This one works too, for uppercase letters

>>> def shifted(letter, shift):
...  return chr(ord('A') + (ord(letter) + shift - ord('A')) % 26)
... 
>>> shifted('C', 3)
'F'
>>> shifted('Z', 3)
'C'
>>> shifted('X', 3)
'A'
>>> shifted('M', 3)
'P'
>>> shifted('M', -3)
'J'
>>> shifted('A', -3)
'X'
>>> shifted('A', -3000000)
'K'
Gribouillis 1,391 Programming Explorer Team Colleague

Well, x + y is transformed into x.__add__(y) if x has a __add__ method. If it doesn't, but y has a __radd__ method, it's transformed into y.__radd__(x) . So all you need to do is to define __add__ and possibly __radd__ methods in your classes.

Gribouillis 1,391 Programming Explorer Team Colleague

Use the 'key' argument of the 'sort' method like this

def score(item): # define a score function for your list items
    return item[1]

r =[(300, 4), (5, 6), (100, 2)]
r.sort(key = score) # sort by ascending score
print r
"""
my output -->
[(100, 2), (300, 4), (5, 6)]
"""
Gribouillis 1,391 Programming Explorer Team Colleague

The explanation is that the code in a class body is executed when a module is loaded, like code at module level, while code in a function or method is only executed when the function is called. So in your last example, the print statement is executed when you create a B instance, and not when class B is defined.
Of course, if a class definition is included in a function's body, its code is executed each time the function is called and not when the module is loaded.

HiHe commented: Thanks for the help +2
Gribouillis 1,391 Programming Explorer Team Colleague

I checked my machine
it got tk and tcl installed,
then I installed tk-devel and tcl-devel
then install python again
it is not working

I didn't say you should install python 2.6, I said you should install it from source following the instructions of the README file concerning tkinter and installation of multiple versions of python.

Gribouillis 1,391 Programming Explorer Team Colleague

Your picture doesn't show the version of tcl/tk, but the version of tkinter. To see the version of tcl/tk, you must look the packages tcl and tk. On my system (mandriva 2010), the version is 8.6.

Then you should install the packages tcl-devel and tk-devel, download python 2.6 source code and build from source.

About upgrading your system: when you install a linux system, you should make a separate partition for the mount point /home , because this allows you to reinstall a new system without changing the content of /home. This way, you keep your data easily. So if your /home is on a separate partition, you should be able to reinstall your system.
Another thing you can do: if all your data in your home folder, say /home/gunbuster, then you can create an archive file of your whole home folder. For this, as administrator, you issue the following commands in a console

cd /home
tar czf gunbuster.tgz gunbuster

Then look at the size of the file gunbuster.tgz. If it's not too big, you should be able to save it on a usb key (it may take some times) or on a separate hard drive. You can even make more than one copy. Then you install a new linux system (with /home in its own partition). In your new system, you put gunbuster.tgz in /home/gunbuster, and you do

cd
tar xzf gunbuster.tgz

Then the folder /home/gunbuster/gunbuster should contain all your previous data. You can …

Gribouillis 1,391 Programming Explorer Team Colleague

You must NEVER remove the version of python that comes with a linux distribution, because the system uses python scripts which were written for this version of python.

In the README file of the python 2.6.2 sources, I found this

Tkinter
-------

The setup.py script automatically configures this when it detects a
usable Tcl/Tk installation.  This requires Tcl/Tk version 8.0 or
higher.

For more Tkinter information, see the Tkinter Resource page:
http://www.python.org/topics/tkinter/

There are demos in the Demo/tkinter directory.

Note that there's a Python module called "Tkinter" (capital T) which
lives in Lib/lib-tk/Tkinter.py, and a C module called "_tkinter"
(lower case t and leading underscore) which lives in
Modules/_tkinter.c.  Demos and normal Tk applications import only the
Python Tkinter module -- only the latter imports the C _tkinter
module.  In order to find the C _tkinter module, it must be compiled
and linked into the Python interpreter -- the setup.py script does
this.  In order to find the Python Tkinter module, sys.path must be
set correctly -- normal installation takes care of this.

and this

Installing multiple versions
----------------------------

On Unix and Mac systems if you intend to install multiple versions of Python
using the same installation prefix (--prefix argument to the configure
script) you must take care that your primary python executable is not
overwritten by the installation of a different versio.  All files and
directories installed using "make altinstall" contain the major and minor
version and can thus live side-by-side.  "make install" also …
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a code which uses a helper class and a few functions to implement your algorithm. Tell me if it works as you expect

# orderer.py
# tested with python 2.6 and 3.1
from difflib import SequenceMatcher

class Orderer(object):
    "Helper class for the ordering algorithm"

    def __init__(self):
        self.matcher = SequenceMatcher()

    def order(self, alist):
        "orders the list in place"
        if not alist:
            return
        alist[0], alist[-1] = alist[-1], alist[0] # swap first and last elements
        self.rank = 1 # self.rank is the index where unordered elements start
        while self.rank < len(alist): # while there are unordered elements
            self.matcher.set_seq1(alist[self.rank-1]) # the last sublist found
            # find the best match
            index, sublist = max(enumerate(alist[self.rank:], start = self.rank), key = self.key)
            alist[self.rank], alist[index] = alist[index], alist[self.rank]
            self.rank += 1

    def key(self, item):
        "score function for the call to 'max'. The score of an item is its 'ratio'"
        index, sublist = item
        self.matcher.set_seq2(sublist)
        return self.matcher.ratio()

def order(alist):
    "Order a list of lists in place with difflib"
    Orderer().order(alist)

def ordered(alist):
    "Return a new list of lists ordered with difflib"
    other = list(alist)
    order(other)
    return other

if __name__ == "__main__":
    my_list = [[6,5,4],[2,3,5],[1,2,3],[3,4,5],[1,2,3,4]]
    print(str(my_list))
    print(str(ordered(my_list)))

"""
My output --->
[[6, 5, 4], [2, 3, 5], [1, 2, 3], [3, 4, 5], [1, 2, 3, 4]]
[[1, 2, 3, 4], [1, 2, 3], [2, 3, 5], [3, 4, 5], [6, 5, 4]]
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Again, you can use a threading.Condition instance. Here is a program that works with python 2.6 and 3.1. I divided the time.sleep by a factor 10 :)

#!/usr/bin/env python

from threading import Thread, Condition
from contextlib import contextmanager
from random import randint
from time import sleep
import sys

@contextmanager
def acquired(condition):
    condition.acquire()
    try:
        yield condition
    finally:
        condition.release()

num = 0
bound = 1 << 31
numcond = Condition()
pexited = False

class P(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global num, pexited
        n = randint(0, 99)
        while n >= 0:
            x = randint(0, 99)
            with acquired(numcond):
                num += x
                print ("P: +%d --> %d" % (x, num))
                if num >= bound:
                    numcond.notify()
            n -= 1
            sleep(0.030)
        with acquired(numcond):
            pexited = True
            print("P exiting")
            numcond.notify()

class C(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run(self):
        global num, bound
        m = randint(0, 99)
        while m >= 0:
            with acquired(numcond):
                bound = randint(0, 99)
                numcond.wait()
                if num > bound:
                    num -= bound
                    print ("C: -%d --> %d" % (bound, num))
                if pexited:
                    print ("C aborting")
                    return
            m -= 1
            sleep(0.015)
        print ("C exiting")

def main():
    p = P()
    c = C()
    p.start()
    c.start()

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

You can use a threading.Condition object. I usually use this in a 'with' context like this

#from __future__ import with_statement # uncomment if python 2.5
from contextlib import contextmanager
from threading import Condition

@contextmanager
def acquired(condition):
    condition.acquire()
    try:
        yield condition
    finally:
        condition.release()

my_condition = Condition()
filename = "my_file.txt"

class A(object):
    def put_data(self, some_data):
        with acquired(my_condition):
            f_out = open(filename, "w")
            f_out.write(some_data)
            f_out.close()

class B(object):
    def get_data(self):
        with acquired(my_condition):
            f_in = open(filename)
            data = f_in.read()
            f_in.close()
        return data

You can also use the same technique to work with a file kept open for both reading and writing. The amount of work done when the condition is acquired should be kept as small as possible because the condition.acquire() statement blocks a thread until the condition object is available.

Gribouillis 1,391 Programming Explorer Team Colleague

The Beautifulsoup module can parse bad html. Also if you have beautifulsoup, you can use the lxml module to parse your bad html code.

Gribouillis 1,391 Programming Explorer Team Colleague

A None value is not displayed by the python shell, as in this example

>>> value = None
>>> value
>>>

A more useful thing to do would be to raise an exception when the number of iterations becomes too big. For example

def newton(f,x,feps,max_it):
      it=0
     def fprime(x):
           return (f(x+feps/2.0)-f(x-feps/2.0))/feps
     while abs(f(x))>feps:
            x=x-f(x)/fprime(x)
            it+=1
            if it>max_it:
                raise RuntimeError("Too many iterations.")
     return x
Gribouillis 1,391 Programming Explorer Team Colleague

Consider this

>>> import datetime
>>> value = datetime.date.today()
>>> print(value)
2009-12-27
>>> value
datetime.date(2009, 12, 27)

When you call print(value) , the string printed is the string resulting from the call str(value) , or equivalently, the string returned by the method __str__() of the class. On the other hand, when the interpreter displays the value (without print), the string actually printed is the string resulting from the call repr(value) , or equivalently the string returned by the method __repr__ . The rule in python, is that when this is possible, the __repr__ method should return an expression which, if evaluated, would allow to reconstruct a new copy of the object. The datetime.date class follows this rule. Many classes don't because they contain too complex data or because their author neglected this feature.

mahela007 commented: Informative as usual +1
Gribouillis 1,391 Programming Explorer Team Colleague

Also on my screen, 30x20 looks better than 24x25.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a widget with the 600 buttons

from Tkinter import*
root = Tk()
frame = Frame(root)

frames = []
buttons=[]
for i in range(24):
    f = Frame(frame)
    frames.append(f)
    for j in range(25):
        n = 25 * i + j
        b = Button(f, text= "%03d" % n)
        buttons.append(b)
        b.pack(side="left")
    f.pack(side="top")
frame.pack(side="top")
                   
root.mainloop()
Gribouillis 1,391 Programming Explorer Team Colleague

I suggest a button array

buttonlist = []
for i in range(600):
    buttonlist.append(Button(frame, *various_options))

Also, to change the image, i suggest something like

button.config(image=...)

but I normally don't use tkinter, so I'm not sure. This link may help.

Gribouillis 1,391 Programming Explorer Team Colleague

You don't have to type all 600 ! What code would you type to create only one ?

Gribouillis 1,391 Programming Explorer Team Colleague

You could use

def find_dupe(L):
    if len(L) == 0:
        return False
    elif L[0] in L[1:]:
        return True
    else:
        return find_dupe(L[1:])
Gribouillis 1,391 Programming Explorer Team Colleague

Looking at the pictures here, the algorithm seems pretty straightforward, starting with a vector of 2 points A and B

def draw_dragon(A, B, depth):
    if depth == 0:
        draw segment A, B
    else:
        compute point C
        draw_dragon(A, C, depth - 1)
        draw_dragon(B, C, depth - 1)

point C is the 3rd vertex of the triangle in the generation 2 picture. The ordering of the vertices in the calls to draw_dragon takes care of the orientation.

Gribouillis 1,391 Programming Explorer Team Colleague

Congratulations ! Can you mark the thread as solved ?

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps your problem comes from the fact that you are trying to access an attribute. You should try to define an accessor method

class RFAMessageWrapper {
    ...
   ??? getService(){
      return service;
  }
  ...
};

and call msg.getService() ?

Gribouillis 1,391 Programming Explorer Team Colleague

You didn't understand my design above. It's not a singleton, the variable is only used temporarily when wrapping an object (by the way, I should have used RFAMessageWrapper instead of RFAMessage).

I can't tell you if your usage of SWIG_NewPointerObj is correct, but you can ask SWIG
how it wraps a RFAMessageWrapper*. For this as I said above, you can declare a pair

RFAMessageWrapper* foo;

RFAMessageWrapper* get_foo(){
    return foo;
}

(just for testing purposes) and you declare the function

RFAMessageWrapper* get_foo();

in your swig interface file. Then your run swig and you look in the c++ program generated by swig how swig wrote the wrapper function wrap_get_foo (or a similar name). The code for this function shows you how swig makes a python object with a RFAMessageWrapper*.
If you follow my instructions, please post the c++ code of the wrapper function.

Gribouillis 1,391 Programming Explorer Team Colleague

I don't know the solution, but I once designed a hack which you should try: You declare a static variable somewhere and an accessor function without arguments for this variable like this

RFAMessage *theVariable;

RFAMessage* getTheVariable(){
    return theVariable;
}

Now you declare getTheVariable in your swig interface file, and swig will generate a python function getTheVariable() which returns a python object wrapping the pointer read in theVariable.

Back to your c++ code, you store a pointer to this python function generated by swig and you can use it to wrap a pointer

PyObject* getTheVariablePythonVersion;

PyObject* mywrapRFAMessage(RFAMessage* msg){
    theVariable = msg;
    return PyObject_CallFunctionObjArgs(
                   getTheVariablePythonVersion, 0);
}

There may be thread issues if different threads want to use theVariable. It looks complicated, but it should allow you to wrap an object without using swig's api.

Also you can look at the code generated by swig for the function getTheVariable and this should tell you how to properly wrap a RFAMessage pointer.

Gribouillis 1,391 Programming Explorer Team Colleague

Im not sure, but I think you should wrap msg2 into a new python object yourself with SWIG_NewPointerObj . You can put only python objects in a call to a python function. Try to google for use examples of SWIG_NewPointerObj. You must pass your c++ pointer and a swig reference to the wrapped type.

Gribouillis 1,391 Programming Explorer Team Colleague

Ok, replace the browse function by this one

def browse_swagbucks(variable):
    """browse_swagbucks(variable) -> a subprocess.Popen object
    Start firefox with a query to swagbucks.com in a separate process."""
    command = [FIREFOX, '-p',  PROFILE, '-no-remote',
       'http://swagbucks.com/?t=w&p=1&q=' + str(variable)]
    print( " ".join(command))
    browser = sp.Popen(command)
    return browser

It will print the command on the output before it tries to run it. Then see if you can run this command in a windows command shell yourself. Also post the command here.

Gribouillis 1,391 Programming Explorer Team Colleague

It seems that your program cannot find firefox.exe. Try to locate this file manually in your file system (probably in C:\Program Files .... Then put the whole path

FIREFOX = r"C:\Program Files ..."

at the top of the program.

Gribouillis 1,391 Programming Explorer Team Colleague

Okay so whats the altered code, because i hve no idea how to do that.

You can write

def make_variable(word_list):
    return "+".join(random.sample(word_list, 4))

I just learned about random.sample in the python documentation.

Gribouillis 1,391 Programming Explorer Team Colleague

@Gribouillis
Shouldn't line 39 test start + 3 against the length of the list?
We're going to be referencing array elements that high.

Yes, you are right, I missed that. It was woooee's idea to shuffle the list once
and take subsequent groups of 4 words. I don't think it's a very good method, because a word can't be repeated until all the words have been chosen once. We should probably choose 4 random positions in the list instead.

Gribouillis 1,391 Programming Explorer Team Colleague

Here is a working version. See how function parameters and return values are used to answer your questions.

import time
import random
import subprocess as sp

FIREFOX = 'firefox.exe'
PROFILE = 'myprofile'
TIME_MINI = 3 * 60
TIME_MAXI = 8 * 60

def main():
    if prompt_do_we_start():
        word_list = open("wordlist.txt").readlines() # read the file only once
        make_variable.start = len(word_list)
        while True:
            variable = make_variable(word_list)
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval()

def prompt_do_we_start():
    """prompt_do_we_start() -> True or False
    Prompt the user if he/she wants to run SwagBot."""
    while True:
        print ''
        print 'Would you like to run the SwagBot now? [Y/N] ONLY'
        dec = raw_input("--> ")
        if dec == 'Y':
            return True
        elif dec == 'N':
            print("Bye...")
            return False
        else:
            print("Please enter Y or N")

def make_variable(word_list):
    """make_variable -> a string of 4 random words separated by +"""
    start = make_variable.start
    if start >= len(word_list):
        random.shuffle(word_list)
        start = 0
    four_random_words = [word_list[x] for x in range(start, start + 4)]
    make_variable.start = start + 4   ## ready for next 4 random words 
    return "+".join(four_random_words)

def browse_swagbucks(variable):
    """browse_swagbucks(variable) -> a subprocess.Popen object
    Start firefox with a query to swagbucks.com in a separate process."""
    browser = sp.Popen([FIREFOX, '-p',  PROFILE, '-no-remote',
       'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
    return browser    

def interval():
    """interval() -> None. Pause the program during a random period of time"""
    sec = random.randint(TIME_MINI, TIME_MAXI)
    print("wait %d seconds ..." % sec)
    time.sleep(sec)

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

Woooee is right. The correct structure to implement

do this
do that
loop again after a random time

is

while True:
    do_this()
    do_that()
    wait_a_random_time()

This is very different from 2 functions calling each other in an infinite recursion. So the proper design for your program is

import time
import subprocess as sp

def main():
    if prompt_do_we_start():
        while true:
            variable = make_variable()
            browser = browse_swagbucks(variable)
            time.sleep(15)
            browser.terminate()
            interval = choose_random_time(3 * 60, 8 * 60)
            time.sleep(interval)

def prompt_do_we_start():
    pass # TODO

def make_variable():
     pass # TODO

def browse_swagbucks(variable):
    pass # TODO

def choose_random_time(mini, maxi):
    pass # TODO

if __name__ == "__main__":
    main()
Gribouillis 1,391 Programming Explorer Team Colleague

You should not write except: clauses without targeting a specific exeption. For example if you're reading user input and you're expecting a number and the user types "hello", then float("hello") will raise a ValueError. You can catch it with except ValueError .
There are many good reasons not to use except: alone. One of them is that when there is a bug in a python program, python will raise an unexpected exception. This exception will not be caught and you will have a nice tracebak in the output, which tells you where is your error. If you catch all exceptions, you will not see the traceback, and you will waste time finding the bug. In python, NOT catching exceptions is a powerful debugging tool. There are other reasons too.

Gribouillis 1,391 Programming Explorer Team Colleague

Perhaps you could follow this kind of design (if I understand correctly the meanings of the arguments to blastall)

#!/usr/bin/env python
# myscript.py
import subprocess as sp
from os path import join as pjoin

def name_pairs():
    "yield a sequence of pairs (input file name, output file name)"
    for i in xrange(1, 2222):
        yield ("fam%d.mcl.fas" % i, "output%d" %i)


def path_pairs(input_dir, output_dir):
    "yield a sequence of pairs (input path, output path)"
    for iname, oname in name_pairs:
        yield pjoin(input_dir, iname), pjoin(output_dir, oname)

def commands(input_dir, output_dir, db_path):
    "yield the commands to run"
    for ipath, opath in path_pairs:
        yield "blastall -p blastp -i %s -d %s -o %s" % (ipath, db_path, opath)

def run_commands(input_dir, output_dir, db_path):
    for cmd in commands(input_dir, output_dir, db_path):
        process = sp.Popen(cmd, shell=True)
        process.wait()


def main():
    input_dir, output_dir, db_path = sys.argv[-3:]
    run_commands(input_dir, output_dir, db_path)

if __name__ == "__main__":
    main()

You could run this script in a shell as myscript.py input_dir output_dir db_path Also you should create a fresh directory as output_dir.

Gribouillis 1,391 Programming Explorer Team Colleague

Some info are missing in your posts:

1) What is the command that you want to run for each file ? I read a few google results about pbs scripts, and may be you want to run commands like qsub script on the command line. So the question is how would you run muscle by hand if you had only one file to process. Also if the job must be completed for 1 file before you start the next file, how do you know that the job is finished ?

2) What are your file names ? are they all in the same directory ?

Gribouillis 1,391 Programming Explorer Team Colleague

This code IS crap. What is it supposed to do ? First bugs: getRandEntry is called before it is defined (in the while True). The for interval ... loop should be removed. Also did you create a profile named myprofile for firefox ? If you're on windows (which seems to be the case), 'firefox' should probably be replaced by firefox.exe. The * 4 is meaningless. Also can you attach wordlist.text to a post ?

Hint: for each function, and for the script, write a docstring describing what it does.

Gribouillis 1,391 Programming Explorer Team Colleague

I discovered this new editor geany. It could be worth trying.