this is my code:

import os,sys
import random
import webbrowser
import time
import subprocess as sp

cls=os.system("cls")
title=os.system('title Hit any key to start searhing!')

while True:
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theRandoms = []
        theRandoms.append(random.choice(wordList)) * 4
        startLink(theRandoms)
        return theRandoms
                
    
def startLink(theRandoms):
        child = sp.Popen(['firefox', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(theRandoms)])
        time.sleep(15)
        child.terminate() #where taskkill for python goes
        for interval in range(180, 481): #180 seconds = 3 mins, 480 seconds = 8 min
        #for loop is to make the random 3min-8min interval between searches
             time.sleep(interval)
             getRandEntry()

I think I passed the variable theRandoms to the second function correctly but im not sure i need the return statement.

can someone tell me how to make this code work because its not working. also if possible how to make it a bit more effecient because i think my code is crap right now :/

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.

getRandEntry() calls startLink(theRandoms) which calls getRandEntry() which will create and infinite loop.

getRandEntry() calls startLink(theRandoms) which calls getRandEntry() which will create and infinite loop.

That's intentional, this macro is intended for long periods of time's use.

Also, I made a list of things i want the program to do as a comment, and defined my functions before calling them.

import os,sys
import random
import webbrowser
import time
import subprocess as sp

cls=os.system("cls")
title=os.system('title Hit any key to start searhing!')

'''

	This program basically goes through a process (well i want it to.)
	
	1) Start a main prompt that asks you to start or not
	2) Make a variable that has 4 random words from a text file
	3) start firefox.exe to "http://swagbucks.com/?t=w&p=1&q=" and after
				the equal sign, the variable with the 4 terms.
	4) Then it should wait 15 seconds (for loading the webpage, and such)
	5) Close firefox.exe 
	6) Loop again AFTER a random 3 minute to 8 minute wait
	
'''

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theRandoms = []
        theRandoms.append(random.choice(wordList)) #if theres no *4 on this line how do i append the variable 4 #times each time with a different random word from the wordlist?
        return theRandoms
        startLink(theRandoms)
                
    
def startLink(theRandoms):
        child = sp.Popen(['firefox.exe', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(theRandoms)])
        time.sleep(15)
        child.terminate() #where taskkill for python goes
        for interval in range(180, 481): #180 seconds = 3 mins, 480 seconds = 8 min
        #for loop is to make the random 3min-8min interval between searches
             #time.sleep(interval)

#also without the for range() loop how do i get a random time between 3 mins and 8 mins?

             getRandEntry()
             
while True:
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

I also attached my wordlist.exe.

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()

That's intentional, this macro is intended for long periods of time's use.

You will soon reach the maximum recursion limit. Use a while loop instead as Gribouillis suggested. Also, you can read the word file once into memory, shuffle it to some random order, and then take the words in groups of 4.

word_list = open("wordlist.txt").readlines()
random.shuffle(wordlist)

start = 0
go_on = ""
while go_on != "no":
    four_random_words = [word_list[x] for x in range(start, start+4)]
    start += 4   ## ready for next 4 random words 
    
    ## then send four_random_words to function to start Firefox
    
    ##  sleep for random time, 3 to 8 minutes
    time.sleep(random.randint(3, 8) * 60)
    go_on = raw_imput("Do you want to continue (yes or no) ")
    go_on = go_on.lower()

I combined both of you guys's scripts and got this.

This is what I got:

import time
import random
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()

def prompt_do_we_start():
##im lost here too..if its 'y' then how do i break out of this function and continue on the main() function?
    print ''
    print 'Would you like to run the SwagBot now? [Y/N] ONLY'
    dec = raw_input("--> ")
    if dec == Y:
        pass
    elif dec == N:
        pass
        ##in this spot i'd normally put something to redo prompt_do_we_start() till the user says 'y'
    else:
        ##if else i want it to keep refreshing prompt_do_we_start() so the user can wait on it until 'y' is inputted.

def make_variable():
    word_list = open("wordlist.txt").readlines()
    random.shuffle(wordlist)

    start = 0
    four_random_words = [word_list[x] for x in range(start, start+4)]
    start += 4   ## ready for next 4 random words 

    
    ## then send four_random_words to function to start Firefox
    return (four_random_words)
    ##i don't think return here is right. how do i escape a function and
    ##continue on the main() function up there from the last point i was at?
    ##, the part that called this function


def browse_swagbucks():
    browser = sp.Popen(['firefox.exe', '-p',  'myprofile', '-no-remote', 'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
    

def interval():
    
    ##  sleep for random time, 3 to 8 minutes
    time.sleep(random.randint(3, 8) * 60)


if __name__ == "__main__":
    main()

Oh yeah! i forgot, i need the 4 word variable up there to be seperated by + signs between each word..i forgot to mention that.
how would i do that?

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()

oh cool! may i ask you what the %s and %d things are and do?

The %d in print("wait %d seconds ..." % sec) will be replaced with the numeric value of sec.

I didn't see the %s, but it is used for string values.

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

@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.

I would also have leaned toward re-shuffling for each set of random words. Just as long as you don't re-read the words from the file, you've saved most of the work.

You could also use choice() instead of shuffling, but you'd have to protect against selecting the same word more than once in a set.

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.

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

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.

Okay i replaced the old variable function with that new one.

import time
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):
    return "+".join(random.sample(word_list, 4))

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()

But I got these errors for that code:

Traceback (most recent call last):
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 54, in <module>
main()
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 17, in main
browser = browse_swagbucks(variable)
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 44, in browse_swagbucks
'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
File "C:\Python\lib\subprocess.py", line 621, in __init__
errread, errwrite)
File "C:\Python\lib\subprocess.py", line 830, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

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.

I still get errors,

Traceback (most recent call last):
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 54, in <module>
main()
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 17, in main
browser = browse_swagbucks(variable)
File "C:\Documents and Settings\Sameer\Desktop\Python Creations\Swagbucks Macro v2.5\new swagbot.py", line 44, in browse_swagbucks
'http://swagbucks.com/?t=w&p=1&q=' + str(variable)])
File "C:\Python\lib\subprocess.py", line 621, in __init__
errread, errwrite)
File "C:\Python\lib\subprocess.py", line 830, in _execute_child
startupinfo)
WindowsError: [Error 3] The system cannot find the path specified

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.