Search code examples
pythonloopsif-statementconsole

Python script continuously repeats the first if - else statement


I am trying to have this script find if the file 'save_the_world.txt' exists and print a response accordingly, and create the file if it does not exist. It also sets up the logger. After doing that it is supposed to run another script and then stop. Instead, it prints the response continuously and does not move on.

import os, logging, sys

saveFilePath = 'save_the_world.txt'

logging.basicConfig(filename='game.log', level='DEBUG', 
                    format='%(asctime)s - %(levelname)s - %(message)s')

if os.path.exists(saveFilePath):
    print("Save file found! Welcome back.")
    newPlayer = False
else:
    with open(saveFilePath, 'x') as f:
        f.write("Save file placeholder text.")
    print("Welcome, new player (or deleter of save files)!")
    newPlayer = True

os.system('python core\login.py')

i attempted to add break to the if-statement output lines, no change. I have not found any solutions to my specific problem online.

edit: this file is called start_game.py

edit2: changing import start_game to from start_game import newPlayer had no effect.

edit3: now that I know the cause, is there a way to take the value for newPlayer and allow login.py to read/use it without rerunning the start_game script (and thus looping infinitely)? (I have clearly misinterpreted how the import function works)


Solution

  • Make these 2 changes:

    inside of login.py get rid of the start_game import and instead use sys.argv to access an argument to the script

    import sys
    newPlayer=sys.argv[1]
    

    and in start_game.py change the last line to this:

    os.system(f'python core\login.py {newPlayer}')
    

    This leverages command line arguments allowing you to send the True/False value of NewPlayer to login.py. sys.argv[1] accesses the first command line argument, which in this case is the value of NewPlayer.

    The above should answer your question but you some general advice: without seeing your entire program or the contents of login.py I can't fully comment on the structure of your program, but I'm wondering if it'd be easier to make the contents of login.py a function inside of start_game so you don't have to use command line arguments (which are usually not the way to go). Or you could make the contents of login.py a function then put from login import login at the top of start_game