Why is my python file not working outside of VS Code?

Question:

I’m trying to run a python script as an executable and when I open it, the first input comes up and it just closes after any input. I tried running the .exe file, the .py file and both have this result.
Here’s a short version of the code:

print("Example Text")
start = int(input("""
To start, press 1.
To leave, press 2.""")
a = open("FilesDocumentsFull.txt")
b = open("FilesDocumentsPart 1.txt")
c = open("FilesDocumentsPart 2.txt")
d = open("FilesDocumentsPart 3.txt")
while True:
    print("""Which part do you want to view?
    1. Part One
    2. Part Two
    3. Part Three
    4. All of it
""")
    segment = int(input())
    if segment == 1:
        print(b.read())
    elif segment == 2:
        print(b.read())
    elif segment == 3:
        print(c.read())

I tried removing the while True: statement at the start, putting only the if segment == part in a loop, I reinstalled the .exe file with the new code and it didn’t work. It’s supposed to just loop through asking what file to print and printing the contents of that file.

Asked By: GabeCodes

||

Answers:

I think this happens because you don’t have the files you want to open in your local working directory.

I adapted the code a bit to show this to you. When you double click a python script / an exe file in windows, it opens a terminal only until the program termiantes. Therefore you probably don’t see the error message.

With the adapted code you should see a file not found exception pop up:

import os


while True:
    try:

        start = int(input(""" To start, press 1.  To leave, press 2."""))
        a = open("FilesDocumentsFull.txt")
        b = open("FilesDocumentsPart 1.txt")
        c = open("FilesDocumentsPart 2.txt")
        d = open("FilesDocumentsPart 3.txt")
        print("""Which part do you want to view?
        1. Part One
        2. Part Two
        3. Part Three
        4. All of it
        """)

                
        segment = int(input())
        if segment == 1:
            print(b.read())
        elif segment == 2:
            print(b.read())
        elif segment == 3:
            print(c.read())

    except Exception as e:
            print(f'an exception occurred: {e}')
            
            print(os.getcwd())




The current working directory is printed when the exception occurs.

You can fix your problem by replacing the relative paths (e.g., FilesDocumentsFull.txt) by absolute paths (e.g., C:Users...FilesDocumentsFull.txt).

When you are not executing your code inside your IDE, you should execute it in a terminal emulator (e.g. powershell), by starting powershell, navigating to the directory that contains your python script, and typing [path/to/python3] [filename.py], e.g. python3 test.py.

Answered By: mutableVoid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.