Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use errno?
#1
i have searched the internet and found 50 code examples for errno here:
(1) Python errno.ENOENT() Examples,
(2) Using Python errno,
(3) Working with Exception in Python
but with more or less identical syntax:
try:
			... ... ... ...
		except OSError as e:
			if e.errno != errno.ENOENT:
Is there no other way than using try:?

I need to run this code successfully:
#! /usr/bin/python
import os
import errno
fileInfo = 0
''' There is supposed to be a file, outPrime.txt. 
If the file is not in the directory, the system
generates an errno and reports FileNotFoundError.
How to bypass this report and continue, to create
a file outPrime.txt if there isn't any, but exit
if there is one?
I am trying to achieving something like the FAUX
codes below:'''
fileInfo = os.stat('outPrime.txt')
catch = os.errno.errorcode(os.stat('outPrime.txt'))
print(catch) '''
Freedom is impossible to conceive.
Books that help:
Dale Carnegie's How To Win Friends And Influence People and Emilie Post's Etiquette In Society, In Business, In Politics, And At Home
Have a good day :)
Reply
#2
(Oct-03-2018, 03:30 PM)bkpsusmitaa Wrote: I need to run this code successfully:
#! /usr/bin/python
import os
import errno
fileInfo = 0
''' There is supposed to be a file, outPrime.txt. 
If the file is not in the directory, the system
generates an errno and reports FileNotFoundError.
How to bypass this report and continue, to create
a file outPrime.txt if there isn't any, but exit
if there is one?
I am trying to achieving something like the FAUX
codes below:'''
fileInfo = os.stat('outPrime.txt')
catch = os.errno.errorcode(os.stat('outPrime.txt'))
print(catch) '''

Well, in Python you can't (not sure you can in any language, but I may be mistaken). The purpose of try/except block is to catch an exception - which occurs on errors that canot be handled otherwise
Output:
----> 1 os.stat('not_in_python') FileNotFoundError: [Errno 2] No such file or directory: 'not_in_python'
This is the standard Python handling mechanism, and if you don't want to use it - then probably Python is not a language for you Naughty
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
You want to do one thing if the file exists, and something different if it doesn't exist, right? That's what try/except is for, it literally does one thing, and then does something else if there's a problem doing what you wanted.

Or, use pathlib, which is very good at working with paths and their contents: (https://docs.python.org/3/library/pathlib.html)
>>> import pathlib
>>> path = pathlib.Path("imaginary_file.spam")
>>> path
WindowsPath('imaginary_file.spam')
>>> path.exists()
False
Reply
#4
Thank you, Mr. Nilamo for posting your suggestions. I was thinking in terms of if-else.
(Oct-03-2018, 04:14 PM)nilamo Wrote: You want to do one thing if ... and something different if it doesn't exist ... then does something else if there's a problem doing ... pathlib ...
Your very sentence says that Smile we could use if-else.
pathlib? Ah! Thanks, Mr. Nilamo. Any other alternatives? Any ideas?
Freedom is impossible to conceive.
Books that help:
Dale Carnegie's How To Win Friends And Influence People and Emilie Post's Etiquette In Society, In Business, In Politics, And At Home
Have a good day :)
Reply
#5
For example, simplifying and debugging my faux codes?
#! /usr/bin/python
import os
import errno
catch = errno.errorcode(os.stat('outPrime.txt'))
print(catch)
someone Wrote:This is the standard Python handling mechanism, and if you don't want to use it - then probably Python is not a language for you (complete with a Naughty emoji)
This betrays a sign of dogmatism, of my way or the highway kind of attitude. If unchecked, gradually escalates into coterie-ism and bullying. Something that ultimately destroys the vibrancy of any group or community. Administrators and Moderators should ensure that such attitudes are not encouraged.

Regarding my requirement:
Ultimately, the choice is of the Python library-programmers. If a simpler way, when envisaged, can't be devised quickly, then Python won't be dynamic enough, despite its greater flexibility and promise over the c programming language. Like c stagnated by its rigidity, Python too may stagnate. And may ultimately be superseded.

A programming language will have to eventually evolve to be easy like normal language, with few additional reserved keywords, and should not require additional learning than knowing Digital Logic and writing a Flow Chart. An extension of ourselves without its receiving special attention. Like our eyes. Ears. Our brains. This is the Evolutionary Flow Chart of Digital Computing: Into Augmented Intelligence.

Whether Python will participate in that evolution or be satisfied by being only a step is ultimately up to the library programmers.
Freedom is impossible to conceive.
Books that help:
Dale Carnegie's How To Win Friends And Influence People and Emilie Post's Etiquette In Society, In Business, In Politics, And At Home
Have a good day :)
Reply
#6
Please, state clearly what your ultimate goal is, so we can suggest best solution/approach.
If you just want to create empty txt file if it does not exists, even something simple like following snippet would do
with open('outPrime.txt', 'a') as f:
    pass
i.e. if file does not exists it will be created.
if you just want to check the file exists you can use os.path.exists()
In any case keep in mind the possible racing condition later on in the code (i.e. even if you created it at some point, there is no guarantee it still exists when you try to access it).
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Please don't pm moderators or admin you can share questions with the forum.
if you are getting an exception, then that means the file is not in your system.
you can use if/else as you ask in your post, by first checking for the existence of the file as your condition:
One way is to use pathlib (python 3.6 or newer):
from pathlib import Path
filename = Path('/somewhere/outPrime.txt')
if filename.exists():
    # file ok continue here
    ...
else:
    print('file {} does not exist'.format(filename.name))
    # or if new python f-string:
    print(f'file {filename.name} does not exist')
Reply
#8
(Oct-04-2018, 08:48 AM)buran Wrote: Please, state clearly what your ultimate goal is...
Of course, Sir, Mr. buran. i definitely will. But you have to assure me that you and the other experienced and senior members won't give me the lines directly. But you won't be superficial either, advising to "Go read the Manual".
Just direct me enough to look at the Python References and Manuals and some example codes. i would pick up the rest. If i can't, i shall ask for your suggestions. You shall provide me with only bare minimum guidance / links as i require. But never, complete lines.
The book i am following, Jamie Chan's Learn Python in One Day... has a simple code for checking whether a number is a prime number.
i have used the simple program as the foundation upon which i plan to go deeper into Python and build my experience.
Needless to repeat, i don't visualise myself as a programmer, but a knowledge seeker. My kind of Programming Language, as stated above, has not yet arrived. i am just seeking Knowledge for the sake of knowledge. Because Stagnation is Death.
The concerned program is like this:
def checkIfPrime (numberToCheck):
      for x in range(2, numberToCheck):
            if (numberToCheck%x == 0):
                  return False
      return True
I have made the program progressively user-controlled to some extent, as you shall shortly find.

But finally, i want it to be so controlled that i could run the entire program from GUI via Glade GUI. i should be able to pause the computation, close the program after having run it for sometime, then shut down the system. Then later on power ON the system and run the program from where i had previously left off. Just like writing a novel in a Text Editor across multiple boots.

But one has to download the whole directory, and run the program from there.

I am presently stuck at the disk Management program. For the required files to run simultaneously i need to have something similar to forking a terminal in Linux. Two or more program threads running simultaneously (although that is really Hardware multiplexing), without one affecting the other in real-time, but they remain connected at the end of the day.

The disk Management program has to run so that as soon as the data file reaches 10KB it will rename the current outPrime.txt to numDone.txt and begin writing another outPrime.txt afresh. So i will continue to have above-mentioned variable x up to the current value recorded until i close the program and shut-down; then begin from there when i choose to, across multiple boots. i will gradually reach there, i am certain. Then Glade GUI.

I have uploaded the concerned files here in Google Drive so that the present thread remains uncluttered.

(Oct-04-2018, 10:47 AM)Larz60+ Wrote: Please don't pm moderators or admin you can share questions with the forum.
Smile Smile No, Sirs. Not for codes. Smile Never. You may remove the codes before I note them. Read them.
Just ideas. Like this, here: Regarding my requirement:. Only this will make my earlier indication meaningful.
Freedom is impossible to conceive.
Books that help:
Dale Carnegie's How To Win Friends And Influence People and Emilie Post's Etiquette In Society, In Business, In Politics, And At Home
Have a good day :)
Reply
#9
I've read this whole thread, some of it a couple times, and I'm not clear on what the question is. Do you just want https://docs.python.org/3/library/os.pat...ath.isfile ? If not, please be more specific and concise, and describe the goal rather than the step (the step here is errno).
Reply
#10
(Oct-04-2018, 04:11 AM)bkpsusmitaa Wrote: This betrays a sign of dogmatism, of my way or the highway kind of attitude.
I disagree. It shows that the python community is different from the perl community. In perl, any particular thing you want to do, can be done in dozens of different ways. If you ask 10 perl programmers how to do something, you'll get 15 different ways to do it.

The Python community is built more around having a small number of obvious solutions, instead of many wacky ways to do something.

All that said, it looks like the original question was answered. If it hasn't, please explain what problem you're trying to solve, what you've tried, and what errors you're getting. Otherwise, it looks like this thread is devolving into troll territory, and it'll be locked if we continue in that direction.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020