но флешка не стартует, просто курсор мигает
а это не флешка виновата, просто образ на вашей машине не запускается. почему – отдельный вопрос
может стоит чем то другим записывать?
записывайте тем, где
запись проходит, вроде все ок
и нет ошибок, как выше (bad file descriptor)
а что это значит PhysicalDrive0
от интерфейса программы зависит. в Windows есть несколько вариантов открыть один и тот же диск. Самое простое – по букве, можно даже с правами пользователя. Но может отвалиться, как у вас на скриншоте выше. Более экзотический вариант – по имени типа PhysicalDrive%, такое умеет, например, WinHex и некоторые другие редакторы. Наверняка Rufus тоже так открывает, но для красоты показывает диск по букве. Ну и самый экзотический – по полному пути, включающему номер USB порта, серийник флешки и т.д. Вряд ли найдется программа, что покажет такой полный путь среди вариантов открытия диска, но из программного кода – один из наиболее надежных способов найти вообще все диски.
Can’t launch Jupyter Notebook
I tried to install tensorflow then the numpy doesn’t work. So I reinstalled numpy then jupyter notebook doesn’t work at all. Whenever I open or create a new ipynb file the service will be diconnected and such error pops out:
Bad file descriptor (D:bldzeromq_1605919615529worksrcepoll.cpp:100)
Then jupyter crashes 🙁
Attach a screen shot
To Reproduce
- launch the jupyter notebook
- go to the notebook page (so far everything seems good)
- open a ipynb file
- lose connection, error pops out in the powershell prompt shell
Expected behavior
Open an ipynb file normally.
Screenshots
This is the error from the prompt
Desktop (please complete the following information):
- Windows 10 Pro
- Anaconda Powershell Prompt (mini) 4.9.2
- Jupyter Notebook 6.1.6
Additional context
I uninstalled jupyter and conda and re-install them but it doesn’t work. I still get the same error.
I am using a scientific software including a Python script that is calling os.system()
which is used to run another scientific program. While the subprocess is running, Python at some point prints the following:
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
I believe that this message is printed at the same time as os.system()
returns.
My questions now are:
Which conditions can lead to this type of IOError? What does it exactly mean? What does it mean for the subprocess that has been invoked by os.system()
?
asked Oct 7, 2011 at 10:54
2
You get this error message if a Python file was closed from “the outside”, i.e. not from the file object’s close()
method:
>>> f = open(".bashrc")
>>> os.close(f.fileno())
>>> del f
close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor
The line del f
deletes the last reference to the file object, causing its destructor file.__del__
to be called. The internal state of the file object indicates the file is still open since f.close()
was never called, so the destructor tries to close the file. The OS subsequently throws an error because of the attempt to close a file that’s not open.
Since the implementation of os.system()
does not create any Python file objects, it does not seem likely that the system()
call is the origin of the error. Maybe you could show a bit more code?
answered Oct 7, 2011 at 11:13
Sven MarnachSven Marnach
567k117 gold badges934 silver badges834 bronze badges
11
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print(output_file.read())
In that code, I want to read the file, but I use mode wb
instead of r
or r+
vvvvv
23.8k19 gold badges48 silver badges75 bronze badges
answered Nov 30, 2015 at 18:38
Aminah NurainiAminah Nuraini
17.8k8 gold badges88 silver badges106 bronze badges
You can get this error if your Ransomware Protection is enabled on your working directory. Windows does not allow any third party applications to make changes to files if the directory is protected by Ransomware Protection which comes with windows. You can rectify this by going to “Windows Security -> Virus and Threat Protection -> Manage Ransomware Protection -> Allow an app through controlled folder access”
Then add “Python[version].exe” by clicking Add an allowed app.
Wai Ha Lee
8,55380 gold badges57 silver badges91 bronze badges
answered Aug 1, 2022 at 11:28
5
Before jumping right into the content directly, it’s essential to analyze the topics by asking some What and How questions. What is a Bad file descriptor error in Python? How do they occur? What are the ways that can help in solving this kind of errors? When we answer these questions, we can eventually understand the essence of this content by the end of this article.
When you don’t allow the code to perform the functions related to the file descriptors and the methods used, a Bad File Descriptor Error arises in Python, indicating the wrong way of implementing the code.
Kicking start with the basics always helps in understanding the core of the subject and hence assists in finding solutions to the most complex problems ever.
Cause of Errors Python
It’s salient to know that only by encountering many errors in code will you be highly proficient in the specific programming language. When you come across a new error, you try to detect where that error appeared from. Eventually, you start researching how to rectify the mistake.
There are even high chances of you exploring more and achieving various easier ways to apply the code better. At last, you will end up observing that your skills in the concept and knowledge about the same had grown vast.
Errors ought to occur in any possible programming language. In Python, errors generally occur when a particular code segment is not in compliance with the advised usage. Various errors are commonly faced by programmers, which include indentation, syntax, etc.
Rectifying these errors is no big deal when you review your code thoroughly. Have a complete understanding of the concepts and know enough about the right syntax to be used in the code.
What are File Descriptors in Python?
In Python, file descriptors are integers(positive) that identify the kernel’s open files kept in a table of files. They are generally non-negative values.
If found to be negative, that indicates error or a “no value” condition. They assist in performing various functions related to files. Descriptors, in general, are a unique way that Python follows to manage attributes.
They mainly help in accessing files, other input/output devices like network sockets or pipes.
File descriptors do perform various operations. They include:
- close(fd) – closes a file descriptor
- dup(fd1) – duplicates file descriptor
- fstat(fd) – returns the status of a file descriptor
The procedures mentioned above are elementary, and it’s important to know that file descriptors perform many more significant operations following the concept.
Understanding [Errno 9] Bad File Descriptor Error in Python
Have you encountered the following error message when you run your Python code when defining file directories or similar ones?
IOError:[Errno 9] Bad file descriptor
When you don’t allow the code to perform the functions related to the file descriptors and the methods used, these kinds of issues arise, indicating the wrong way of implementing the code.
Let’s understand this with an example:
<em>>>>file1=open(".bashrc") >>>os.close(file1.fileno()) >>>def file1 close failed in file object destructor IOError:[Errno 9] Bad file descriptor</em>
The below image shows a code with a bad file descriptor error in the Python shell.
In the above code, the del file will delete the reference of the file object specified. Now, as per the code written, the close function was not called. This forces the destructor to close the file. As this resulted in closing a file that wasn’t open in the first place, OS throws an error – Bad file descriptor.
Best Ways to Solve from [Errno 9] Bad File Descriptor in Python
- Make sure you are using a valid file descriptor number. You will get a UNIX or Python Shell- Bad file descriptor error message when you fail using the right file descriptor number. This can cause issues when you open, close or use a file.
- Use the right modes while handling file descriptors. For example to read from the file you need to use the read mode. When you choose the wrong mode, that triggers an error.
- Analyse the concept and then implement the right functions at the right segments of your code.
- Make certain whether the function to be executed through your code was executed already or not.
[Errno 9] Bad File Descriptor in Python Socket Module
Another main area in which this error is seen is in the Python socket – Socket error Bad file descriptor. When dealing with this kind of program, you can notice that you will find a Bad file descriptor error message is seen along with some issues in opening/closing or accessing the socket.
You can tackle this error by finding the right method of executing the function through the prescribed way of performing the function in accordance with the file descriptor.
One common thing that you can notice while handling errors in Python in relevance to files and file descriptors is that many of us fail to follow and implement the proper functions of the file descriptors defined in the code to perform the operations.
In addition to the above-discussed problems, this issue occurs while executing simple print statements too. You should focus on knowing if your specific file descriptors are available in the console that you are running.
This might seem simple when phrased but can cause a huge trauma to the programmer who has invested hours in writing the code. First, make sure that the specifies file descriptors are available in the console in which you run your program.
How to solve Bad File Descriptor in Python Socket module?
One way of handling this error is to calmly ignore the print statements and use alternative segments of code that serve a similar purpose.
Consider the following code –
from time import sleep import socket mcip = "mau5ville.com" port = 25565 magic = "xFE" s = socket.socket() while 1: # Determine whether the server is up or down try: s.connect((mcip, port)) s.send(magic) data = s.recv(1024) s.close() print(data) except Exception as e: print(e) sleep(60)
This error is caused when you specify a function to get executed when it has already completed doing the job. For instance, you order your code to close a file through your long lines of code. It shows an error like:
OSError: [Errno 9] Bad file descriptor
It means that the file defined in the program is already closed automatically while running the code. There lies no use in defining a separate method to perform the same task again.
What is a bad file descriptor?
When we try to perform an operation/activity on closed (non-opened) files, a bad file descriptor error is generated. During such an error, you should look for possibilities where your file may get closed in your code.
What is a standard file descriptor?
In python file descriptors are integers(positive) that do the job of identifying the open files kept in a table of files by the kernel. They are generally non-negative values (0, 1, or 2).
What is Fcntl in Python?
fcntl is a library in Python that controls the file and I/O on file descriptors.
Conclusion
Bad file descriptor mainly arises due to many factors that were discussed in brief above. The main fact is that they occur when the right functions do not perform in association with the file descriptors.
With clear analysis and better knowledge of the concept, one can easily detect these errors and transform the code into a successful one.
References
- Python open() function: file is a path-like object giving the pathname (absolute or relative to the current working directory) of the file to open or an integer file descriptor of the file to wrap.
- socket.socket(): If fileno is specified, the values for family, type, and proto auto-detects from the specified file descriptor.
If you are a developer working with Python, you may have come across the “OSError: [Errno 9] Bad File Descriptor” error. This error can occur when you are working with files or sockets and can be frustrating to debug. In this guide, we will provide a comprehensive solution to troubleshoot this error.
Understanding the Error
Before we dive into the troubleshooting steps, let’s understand what this error means. The “OSError: [Errno 9] Bad File Descriptor” error is raised when a file descriptor that’s not open or is closed is used. A file descriptor is a unique number that identifies a file or socket. When you perform operations such as reading, writing, or closing a file or socket, the file descriptor associated with it is used.
Troubleshooting Steps
Follow these steps to troubleshoot the “OSError: [Errno 9] Bad File Descriptor” error:
Step 1: Check the File Descriptor
The first step is to check the file descriptor associated with the file or socket that’s causing the error. You can do this by printing the file descriptor before and after performing any operations on it. Here’s an example:
import os
# Open a file
file = open("file.txt", "r")
# Print the file descriptor
print(file.fileno())
# Perform operations on the file
# Close the file
file.close()
# Print the file descriptor again
print(file.fileno())
If the file descriptor is different before and after performing operations on it, it means that the file or socket has been closed or is not open. You need to make sure that the file or socket is open before performing any operations on it.
Step 2: Check for Exceptions
The next step is to check if any exceptions are being raised while performing operations on the file or socket. You can use a try-except block to catch any exceptions. Here’s an example:
try:
# Perform operations on the file
except Exception as e:
print("Exception:", e)
If an exception is being raised, it may be causing the “OSError: [Errno 9] Bad File Descriptor” error. You need to fix the exception before proceeding.
Step 3: Use a Context Manager
Using a context manager can ensure that the file or socket is closed properly after performing operations on it. Here’s an example using a context manager:
with open("file.txt", "r") as file:
# Perform operations on the file
By using a context manager, you don’t have to worry about closing the file or socket manually.
Step 4: Use a Different File Descriptor
If none of the above steps work, you can try using a different file descriptor. You can use the os.dup()
function to create a duplicate file descriptor. Here’s an example:
import os
# Open a file
file = open("file.txt", "r")
# Create a duplicate file descriptor
new_fd = os.dup(file.fileno())
# Perform operations on the file using the new file descriptor
# ...
# Close the file
file.close()
FAQ
Q1: What causes the “OSError: [Errno 9] Bad File Descriptor” error?
A1: This error is caused when a file descriptor that’s not open or is closed is used.
Q2: How do I check the file descriptor associated with a file or socket?
A2: You can print the fileno()
method of the file or socket object.
Q3: What is a context manager?
A3: A context manager is an object that defines the methods __enter__()
and __exit__()
. It’s used with the with
statement to ensure that resources are properly managed.
Q4: How do I create a duplicate file descriptor?
A4: You can use the os.dup()
function to create a duplicate file descriptor.
Q5: Can I use the same file descriptor for multiple files or sockets?
A5: No, each file or socket has a unique file descriptor associated with it.
Conclusion
The “OSError: [Errno 9] Bad File Descriptor” error can be frustrating to debug, but by following the troubleshooting steps outlined in this guide, you should be able to resolve the issue. Remember to always check the file descriptor, catch exceptions, use a context manager, and try using a different file descriptor if all else fails.