1

I have the following script that is executed three times but I can't figure out why

#!C:/Python38-32/python.exe
#script.py
from py_get_data_from_game import main
from multiprocessing import Pool

import connect_to_db
import mysql.connector
from mysql.connector import Error

connection = connect_to_db.connect()

user_names = []
passwords = []
    
print('START')  
try:
    connection = connect_to_db.connect()
    if connection.is_connected():
        sql_select_Query = "select * from players"
        cursor = connection.cursor(dictionary=True)
        cursor.execute(sql_select_Query)
        records = cursor.fetchall()

        for row in records:
            user_names.append(row['user_name'])
            passwords.append(row['password'])

except Error as e:
    print("Error while connecting to MySQL", e)
finally:
    if (connection.is_connected()):
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
        
if __name__ == '__main__':
    pool = Pool(2) # two parallel jobs
    results = pool.map(main, zip(user_names, passwords))

Output:

C:\scripts>script.py
START
MySQL connection is closed
START
MySQL connection is closed
START
MySQL connection is closed
remyremy
  • 3,548
  • 3
  • 39
  • 56
  • 1
    You need to have everything from `print('START')` to the end to be inside the `if __name__ == '__main__':` when you are using `multiprocessing`. – quamrana Jul 30 '20 at 19:41
  • That worked! Could you elaborate a little bit why this is needed? (In an answer so I can accept it) – remyremy Jul 30 '20 at 19:47
  • Does this answer your question? [Compulsory usage of if \_\_name\_\_=="\_\_main\_\_" in windows while using multiprocessing](https://stackoverflow.com/questions/20360686/compulsory-usage-of-if-name-main-in-windows-while-using-multiprocessi) – quamrana Jul 30 '20 at 19:53

1 Answers1

1

When you are using multiprocessing, python needs to create as many processes as your program happens to specify, with the same environment (by which I mean imports). It does this by running your script again.

To avoid having spurious code also execute you should put it after:

if __name__ == '__main__':
quamrana
  • 37,849
  • 12
  • 53
  • 71