I wrote a python file in visual studio code with anaconda as the interpreter. I used pyinstaller to turn the file into an exe but when I try to open the exe a cmd window flashes open for a second and then closes. I don't know why it won't open. My program is supposed to read and print out specific data requested by the user from a HDF5 file and it does exactly that in visual studio code. I really just need a way to make it able to be run by someone on a different computer with python not installed.
Here is my entire code I know its probably bad because I don't have much python experience, but it works in visual studio code:
import numpy as np
import h5py
print ("Make sure to move the HDF file to the folder where this program is located.")
valid = "valid"
#gets the file name and checks if file exists
while valid == "valid":
filename = input("\nwhat is the name of the HDF file including the .hdf: ")
try:
with h5py.File(filename,"r") as hdf:
path = hdf.get("/Results/Unsteady/Output/Output Blocks/Base Output/Unsteady Time Series/2D Flow Areas/Flow Area")
break
except IOError:
print ("File not found")
#opens file
with h5py.File(filename,"r") as hdf:
#navigates to file location
path = hdf.get("/Results/Unsteady/Output/Output Blocks/Base Output/Unsteady Time Series/2D Flow Areas/Flow Area")
path_items = list(path.items())
#keeps running until user tells it to stop
run = "y"
while run == "y" or run == "Y" or run == "yes" or run == "Yes":
#user input
while valid == "valid":
choice = input("\nWhich file would you like to get data from? Depth, Face Shear stress, Face Velocity, or Water Surface: ")
choice = choice.lower()
if choice == "depth" or choice == "face shear stress" or choice == "face velocity" or choice == "water surface":
break
else:
print ("Invalid")
#checks the user input then converts the data set into a numpy array
if choice == "depth":
dataset = np.array(path.get("Depth"))
if choice == "face shear stress":
dataset = np.array(path.get("Face Shear Stress"))
if choice == "face velocity":
dataset = np.array(path.get("Face Velocity"))
if choice == "water surface":
dataset = np.array(path.get("Water Surface"))
#gets the shape/size of the dataset
shape = str(dataset.shape)
shape = shape.replace("(","")
shape = shape.replace(")","")
shape = shape.split(",")
timeAmount = shape[0]
pointAmount = shape[1]
timeAmount = int(timeAmount)
pointAmount = int(pointAmount)
timeAmount -= 1
pointAmount -= 1
print ("\nThis data set has",timeAmount,"time values and",pointAmount,"data values.")
#user input
while valid == "valid":
time = input("\nEnter a single time step: ")
try:
int(time)
break
except ValueError:
print ("Invalid")
time = int(time)
while valid == "valid":
minR = input("\nEnter the first (smaller) value in a range of cell locations: ")
try:
int(minR)
break
except ValueError:
print ("Invalid")
minR = int(minR)
while valid == "valid":
maxR = input("\nEnter the second (larger) value in a range of cell locations: ")
try:
int(maxR)
break
except ValueError:
print ("Invalid")
maxR = int(maxR)
#calculates all the numbers in the range between the two numbers
rangeL = []
while minR != maxR:
rangeL.append(minR)
minR += 1
rangeL.append(maxR)
#prints the value at each point
count = 0
for x in range(len(rangeL)):
tempN = rangeL[count]
tempV = dataset[time,rangeL[count]]
print (str(tempN) + "," + str(tempV))
count += 1
#asks the user if they want to get more data
run = input("\nWould you like to enter more parameters to get more/different data? (y/n): ")
if run == "y" or run == "Y" or run == "yes" or run == "Yes":
pass
else:
print ("Goodbye")
break
Probably because you have a code with just a few outputs. That means that the programm executes those lines really fast and eventually closes. Request for an input at the end of your code. That should make the program to stay open.
It worked for me. I used pyinstaller with command: pyinstaller -F file_name.py. It works. Doesn't close fast and asks for the input also.
Related
I'm trying to do a silly little program that will let me open an image given a specific number.
import os
c1= os.startfile('Cat1.PNG')
c2= os.startfile('Cat2.PNG')
c3= os.startfile('Cat3.PNG')
catlist= [c1,c2,c3]
valid= False
def cats(valid):
while not valid:
try:
answer=int(input('Choose a number between 1 and 3'))
valid= True
except ValueError:
print("This is not a number")
if answer >=1 and answer <=3:
print(catlist[answer-1])
else:
print('Wrong value')
del (answer)
cats(valid)
return
cats(valid)
My problem is that my pictures just get all open when I start the program, while I want to open them when I choose a specific number.
The problem with your code is in the part where you assign the os.startfile() function to a variable.
When Python interpreter goes through your code, as soon as it hits the c1= os.startfile('Cat1.PNG') line of code, it executes the command and opens the files immediately.
import os
valid = True
def cats(valid):
while valid:
try:
x = int(input("Enter a number here: "))
valid = False
except ValueError:
print("This is not a number!")
if x == 1:
os.startfile('1.jpg')
elif x == 2:
os.startfile('2.jpg')
elif x == 3:
os.startfile('3.jpg')
else:
print("Wrong value")
valid = True
cats(valid)
There is probably a better and more efficient way to do it, but here is a solution I came up with.
I am working on a stupid yet funny practice program to improve my understanding of OOP in Python.
The program is meant to randomly generate some band names from a randomly selected adjective and another randomly selected noun - producing a lot of hilarious band names.
For the most part, the program works fine, but for some reason, there are some problems with the if-statements and the while loop in the menu(self)- method all the way down in the BandList class.
My hypothesis is that there is something wrong with the nesting of the else-if statements, or that the loop doesn't manage to advance the loop when I call on the self._generateBand() method in line 60 due to some technicality I'm not aware of. Either way, I'm not sure.
However, my question is:
Why does my loop stop at the line self._writeBand() and not continue executing the code that follows? (As shown below)
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #The loop stops here for some reason and asks the same question over and over.
#The program won't execute this part of the code.
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
outfile = input("What do you want to name the file?: ")
self._saveBand(f"{oufile}.txt")
If anyone can help me fix this, I would be super grateful.
In advance: Thank you for your help.
The complete program is pasted in below
import random
class Band:
def __init__(self, name):
self._Bandname = name
def __str__(self):
return f"{self._Bandname}"
def hentName(self):
return self._Bandname
class BandList:
def __init__(self):
self._BandList = []
def _readFile(self, filename1, filename2):
with open(filename1) as infile1, open(filename2) as infile2:
lineAdjective = infile1.read().splitlines()
lineNoun = infile2.read().splitlines()
adjective = random.choice(lineAdjective)
noun = random.choice(lineNoun)
return f"{adjective} {noun}"
def _saveBand(self, filename):
with open(filename, "w") as outfile:
for j, i in enumerate(self._BandList):
outfile.write(f"Nr: {j}\t-{i}\n")
def _generateBand(self):
num = int(input("\nHow many band names would you like to generate?: "))
for i in range(num):
bandname = f"The {self._readFile('adjective.txt', 'noun.txt')}s"
self._BandList.append(Band(name= bandname))
def _writeBand(self):
print("\n========= Genererte bandname =========")
for i in self._BandList:
print(i)
#print(i.hentName())
def _deleteBand(self):
self._BandList.clear()
def _writeGoodbyeMsg(self):
print("\n============ PROGRAM TERMINATING ================")
print("\t- thanks for using the program, goodbye!")
def menu(self):
done = False
while done != True:
print("\n=============== BAND NAME GENEREATOR ==================")
start = input("\nDo you want to generate a list of bandnames? (y/n): ")
if start.lower() == "y":
self._generateBand()
self._writeBand() #This is probably where the bug is...
inp = ("\nDo you want to save these band names? (y/n): ")
if inp.lower() == "y":
utfil = input("What do you want to name the file?: ")
self._saveBand(f"{utfil}.txt")
elif inp.lower() == "n":
self._deleteBand()
inp2 = input("Do you want to generate more band names? (y/n)?: ")
if inp2.lower() == "y":
self._generateBand()
elif inp2.lower() == "n":
done = True
self._writeGoodbyeMsg()
else:
print("Unknown command, please try again")
else:
self._writeGoodbyeMsg()
done = True
if __name__ == '__main__':
new = BandList()
new.menu()
You're missing an input call on your 2nd question for saving the band names. It should be:
inp = input("\nDo you want to save these band names? (y/n): ")
It does work. You just haven't given any values in self._BandList.
Its returning "BandList": null.
I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?
def CreateQuiz(i):
# here i'm creating the keys and values of the "flashcards"
f = open(fileList[i],'r') # using the read function for both files
EngSpanVocab= {} # this converts the lists in the text files to dictionaries
for line in f:
#here this trims the empty lines in the text files
line = line.strip().split(':')
engWord = line[0]
spanWord = line[1].split(',')
EngSpanVocab[engWord] = spanWord
placeList = list(EngSpanVocab.keys())
while True:
num = input('How many words in your quiz? ==>')
try:
num = int(num)
if num <= 0 or num >= 10:
print('Number must be greater than zero and less than or equal to 10')
else:
correct = 0
#this takes the user input
for j in range(num):
val = random.choice(placeList)
spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
if spa in EngSpanVocab[val]:
correct = correct+1
if len(EngSpanVocab[val]) == 1:
#if answers are correct the program returns value
print('Correct. Good work\n')
else:
data = EngSpanVocab[val].copy()
data.remove(spa)
print('Correct. You could also have chosen',*data,'\n')
else:
print('Incorrect, right answer was',*EngSpanVocab[val])
#gives back the user answer as a percentage right out of a 100%
prob = round((correct/num)*100,2)
print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
break
except:
print('You must enter an integer')
def write(wrongDict, targetFile):
# Open
writeFile = open(targetFile, 'w')
# Write entry
for key in wrongDict.keys():
## Key
writeFile.write(key)
writeFile.write(':')
## Value(s)
for value in wrongDict[key]:
# If key has multiple values or user chooses more than 1 word to be quizzed on
if value == wrongDict[key][(len(wrongDict[key])) - 1]:
writeFile.write(value)
else:
writeFile.write('%s,'%value)
writeFile.write('\n')
# Close
writeFile.close()
print ('Incorrect answers written to',targetFile,'.')
def writewrong(wringDict):
#this is for the file that will be written in
string_1= input("Filename (defaults to \'wrong.txt\'):")
if string_1== ' ':
target_file='wrong.txt'
else:
target_file= string_1
# this checs if it already exists and if it does then it overwrites what was on it previously
if os.path.isfile(target)==True:
while True:
string_2=input("File already exists. Overwrite? (Yes or No):")
if string_2== ' ':
write(wrongDict, target_file)
break
else:
over_list=[]
for i in string_1:
if i.isalpha(): ovrList.append(i)
ovr = ''.join(ovrList)
ovr = ovr.lower()
if ovr.isalpha() == True:
#### Evaluate answer
if ovr[0] == 'y':
write(wrongDict, target)
break
elif ovr[0] == 'n':
break
else:
print ('Invalid input.\n')
### If not, create
else:
write(wrongDict, target)
def MainMenu():
## # this is just the standad menu when you first run the program
if len(fileList) == 0:
print('Error! No file found')
else:
print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
print(str(1) ,"Places.txt")
print(str(2) ,"Verbs.txt")
while True:
#this takes the user input given and opens up the right text file depending on what the user wants
MainMenu()
userChoice = input('==> ')
if userChoice == '1':
data = open("places.txt",'r')
CreateQuiz(0)
elif userChoice == '2':
data = open("verbs.txt",'r')
CreateQuiz(1)
elif userChoice == 'Q':
break
else:
print('Choose a Valid Option!!\n')
break
You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script.
Try setting the directory:
import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')
Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in python 3 to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
def Setup():
fw = open('AutoLoader.txt', 'a')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close
break
fw.close
Start()
Try replacing fw.close with fw.close()
It's working on python 3.4
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
fw.close()
break
fw.close()
Setup()
Not knowing what Start() does, it must be ignored in answers, so far...
I wouldn't bother to close the file myself, but let a with statement do the job properly.
Following script works at least:
#!/usr/bin/env python3
def Setup():
with open('AutoLoader.txt', 'a') as fw:
while True:
print("Enter new location to enter")
new_entry = str(input("Start with 'web' if it's a web page\n"))
fw.write(new_entry + "\n")
y = input('New Data? Y/N\n')
if y in ['N', 'n']:
break
#Start()
Setup()
See:
nico#ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
First user's entry
New Data? Y/N
N
nico#ometeotl:~/temp$ ./test_script3.py
Enter new location to enter
Start with 'web' if it's a web page
Another user's entry
New Data? Y/N
N
nico#ometeotl:~/temp$ cat AutoLoader.txt
First user's entry
Another user's entry
nico#ometeotl:~/temp$
Also note that a possibly missing AutoLoader.txt at start would be created automatically.
My code does not write to a file, what am I doing wrong? I am trying to program to continue to ask for products until the user does not enter a product code. I want all products to be saved in the file.
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
contine = input("Press 1 to enter a new product press 2 to leave: ")
if contine == "1":
print("Enter your product information")
information = []
product = input("What's the product code: ")
information.append(product)
description = input("Give a description of the product: ")
information.append(description)
price = input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean)
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close
I got the program working with the following adjustments. See comments for explanations:
store_file = open("Database.txt", "w")
NewProduct = ""
while NewProduct != False:
continue = raw_input("Press 1 to enter a new product press 2 to leave: ")
#Changed to raw_input because input was reading in an integer for 1 rather than a
#string like you have set up. This could be specific to my IDE
if continue == "1":
print("Enter your product information")
information = []
product = raw_input("What's the product code: ")
information.append(product)
description = raw_input("Give a description of the product: ")
information.append(description)
price = raw_input("Enter price of product: ")
information.append(price)
information = str(information)
clean = information.replace("]","").replace("[","").replace(",","").replace("'","")
store_file.write(clean + "\n")
#Added a line break at the end of each file write
elif contine == "2":
NewProduct = False
else:
print("Your input is invalid")
store_file.close() #Added parentheses to call the close function
I'm assuming the problem here is that you're using Python 2, and input isn't doing what you think it does. In Python 2, input evals the input as if it were Python source code, so if someone enters 2, it's going to return the int value 2, not "2". In Python 2, you want to use raw_input, always (eval-ing random user input not being secure/reliable).
Also, while on CPython (the reference interpreter) files tend to naturally close themselves when they go out of scope, you made an effort to close, but forgot to actually call the close method; store_file.close looks up the method without calling it, store_file.close() would actually close it. Of course, explicit close is usually the wrong approach; you should use a with statement to avoid the possibility of forgetting to close (or of an exception skipping the close). You can replace:
store_file = open("Database.txt", "w")
...
store_file.close()
with:
with open("Database.txt", "w") as store_file:
... do all your work that writes to the file indented within the with block ...
... When you dedent from the with block, the file is guaranteed to be closed ...
There are other issues though. What you're doing with:
information = str(information)
information = information.replace("]","").replace("[","").replace(",","").replace("'","")
is terrible. I'm 99% sure what you really wanted was to just join the inputs with spaces. If you switch all your input calls to raw_input (only on Python 2, on Python 3, input is like raw_input on Python 2), then your list is a list of str, and you can just join them together instead of trying to stringify the list itself, then remove all the list-y bits. You can replace both lines above with just:
information = ' '.join(information)