问题
I have a simple function that I use to read the contents of a text file into a Python variable. I use it to import SQL queries. The function takes a parameter that is the path and name of the text file and allows several attempts to get the name right, allowing for typos or mis-spellings. By default, this parameter is set to None. If the file can't be found, the function prints an error message and presents an input() box to allow a new path and filename to be entered. The function then either returns the string (representing the SQL query) or returns None if the file can't be found.
The function is:
def readQueryFromFile(queryPathAndFileName = None):
maxAttempts = 3
for i in range(maxAttempts):
if (queryPathAndFileName is None) or (i > 0):
queryPathAndFileName = input("Enter path and filename for text file contains SQL query: ")
try:
tempFileObject = open(queryPathAndFileName)
tempQuery = tempFileObject.read()
tempFileObject.close()
break
except FileNotFoundError as e:
print("\nA FileNotFoundError occurred.\nError number {0}: {1}. File named \'{2}\' does not exist at that location.".format(e.args[0],e.args[1],queryPathAndFileName))
if i < (maxAttempts-1):
print('\nPlease re-enter path and filename details.\n') # Only say 'Please try again' if not last attempt.
else:
# If query file can't be found then set tempQuery to None
print('\nFailed to find file containing query after {0} attempts.\n'.format(i+1))
tempQuery = None
return tempQuery
The function could be called in a Jupyter notebook cell using:
myQuery = readQueryFromFile(queryPathAndFileName = '/geosgnasoeg/asgogeso.sges')
Clearly, the path and file name is nonsensical and the function presents an error message and a prompt to enter the path and file name again. However, the error messages appear after the input box is displayed as follows:
Enter path and filename for text file contains SQL query: |________|
A FileNotFoundError occurred.
Error number 2: No such file or directory. File named '/geosgnasoeg/asgogeso.sges' does not exist at that location.
Please re-enter path and filename details.
Having the messages appear out of sequence can be confusing. Interestingly, if a second incorrect path and file name is entered, the output realigns itself correctly.
I'm using a Mac running El Capitan and this issues occurs in both Safari and Firefox.
Is there a way to force the output displayed in Jupyter notebook to appear in the correct (i.e. sequential) order?
来源:https://stackoverflow.com/questions/44013247/python-input-box-position-in-jupyter-notebook-is-out-of-sequence