I'm making a macro in python and I need some help.

Basically, it just loads up 4 line entries from a text file and just attaches those 4 things to the end of a URL, and opens firefox to that URL. It then waits a random time between 3min-8min and terminates firefox and loops again.

I think i did something wrong because I'm trying to run it and its not running.

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!')

def main():
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

def getRandEntry(): #this function gets 4 random line entries from wordlist.txt
        WordList = open("wordlist.txt","r")
        randomEntry1 = random.choice(WordList.readlines())
        randomEntry2 = random.choice(WordList.readlines())
        randomEntry3 = random.choice(WordList.readlines())
        randomEntry4 = random.choice(WordList.readlines())
        WordList.close()
        startLink()

    
def startLink():
    QuadEntry = randomEntry1 + "+" + randomEntry2 + "+" + randomEntry3 + "+" + randomEntry4
    child = sp.Popen(['firefox', '-p',  'myprofile', '-no-remote', "http://swagbucks.com/?t=w&p=1&q=" + `QuadEntry`])
    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()

Dani AI

Generated

A few quick fixes and a simple, robust pattern to follow.

Common problems seen in the thread: you never actually run the right code (or you call main() before the functions exist), the four words are picked with repeated calls to readlines() instead of reading once, the sleep loop for interval in range(180,481) is not random, and variables created in one function are referenced in another (scope error). pointed out the missing main call and scope problem; later called main() too early which will raise a NameError.

A clean, safe structure (Python 3) — read the file once, pick four words, URL-encode them, open the browser, wait a random time, repeat:

import random, time, subprocess
from urllib.parse import quote_plus

def pick_words(path, n=4):
    with open(path, 'r', encoding='utf-8') as f:
        words = [w.strip() for w in f if w.strip()]
    return random.sample(words, n)  # use random.choices if duplicates allowed

def open_query(words):
    q = "+".join(quote_plus(w) for w in words)
    url = "http://swagbucks.com/?t=w&p=1&q=" + q
    proc = subprocess.Popen(['firefox', '-p', 'myprofile', '-no-remote', url])
    time.sleep(15)
    proc.terminate()

def main():
    while True:
        open_query(pick_words("wordlist.txt"))
        time.sleep(random.randint(180, 480))

if __name__ == "__main__":
    main()

Notes and troubleshooting

  • random.sample requires at least 4 unique lines; use random.choices or fallback logic if file is small.
  • Use quote_plus to safely encode spaces/special chars for a query.
  • Do not call main() before function definitions; use the if __name__ == "__main__": guard.
  • subprocess.Popen may not always map cleanly to a persistent Firefox window (Firefox can spawn/daemonize). If you need reliable open/close control, consider using a headless browser or automation (Selenium) instead of trying to kill the browser process.
  • Keep file path and encoding in mind; add basic error handling around file access for robustness.

Recommended Answers

All 7 Replies

First of all, in the code you posted, you never run your main function.

how do i do that?

like this:

main()

?

Yes, that should be your last line. That or:

if __name__ == "__main__":
    main()

People tend to use that so if their file is imported as a module, then its functions can be used without the whole program running. But your line is fine, too.

Btw, it still won't work after that. randomEntry1-4 are all local variables that only exist in getRandEntry. They don't exist in startLink. You can either pass them as arguments to startLink (recommended) or make them global variable (bad python user, bad).

Also, getRandEntry is a bit inefficient. You call readlines() 4 times, where you could call it once. I would do it like this:

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theFile.close()
        theRandoms = []
        for i in range(4):
                theRandoms.append(random.choice(wordList))
        startLink(theRandoms) #you'll need to change startLink to make this work

Thanks! thats really cool how you can append to an empty value like that.
I don't know how to give other fuctions arguments yet so can you post an example similar to my program or something like that?

thanks a bunch!~@

Sure.

def printRandEntries(argList):
        for entry in argList:
                print entry
printRandEntries(["boil 'em", "mash 'em", "stick 'em in a stew"])

The function above takes a list as an argument, and then using the for loop, prints out each thing in the list.

Just to let you know, in startLink, the intervals in that bottom for loop won't be that random. The first interval will be 180 seconds, the next will be 181, the next 182, and so on.

Ooh so thats how you do it.

Anyways, um how would be a randomer way of doing what I did?

This is how I remade it so far, i can't help it but i think i wrote something incorrectly...

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!')

main()

def main():
    cls
    print "" 
    title
    raw_input()
    getRandEntry()

def getRandEntry():
        theFile = open("wordlist.txt","r")
        wordList = theFile.readlines()
        theFile.close()
        theRandoms = []
        for i in range(4):
                theRandoms.append(random.choice(wordList))
                startLink(theRandoms) #you'll need to change startLink to make this work

    
def startLink(argList):
        for entry in argList:
            child = sp.Popen(['firefox', '-p',  'myprofile', '-no-remote', "http://swagbucks.com/?t=w&p=1&q=" + `QuadEntry`])
            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()
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.