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("Files\Documents\Full.txt")
b = open("Files\Documents\Part 1.txt")
c = open("Files\Documents\Part 2.txt")
d = open("Files\Documents\Part 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.
CodePudding user response:
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("Files\Documents\Full.txt")
b = open("Files\Documents\Part 1.txt")
c = open("Files\Documents\Part 2.txt")
d = open("Files\Documents\Part 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., Files\Documents\Full.txt
) by absolute paths (e.g., C:\Users\...Files\Documents\Full.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
.