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
3
  • 1
    You need to have everything from print('START') to the end to be inside the if __name__ == '__main__': when you are using multiprocessing. Commented Jul 30, 2020 at 19:41
  • That worked! Could you elaborate a little bit why this is needed? (In an answer so I can accept it) Commented Jul 30, 2020 at 19:47
  • Does this answer your question? Compulsory usage of if __name__=="__main__" in windows while using multiprocessing Commented Jul 30, 2020 at 19:53

1 Answer 1

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__':
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.