using python to open a device for raw writing - python

I'm writing some code to read and interpret the MBR and then the FAT of a pen drive formatted with fat32, everything is going fine, I now want to write to the device at a specific position, so after closing the device I'd opened to read, I try again like this:
dr = file("/dev/disk5","r+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 16] Resource busy: '/dev/disk5'
So i close everything up, and restart the interpreter with sudo (sudo python), and retry all with the same results.
what can I do in order to be able to open the device for write access?
thanks
EDIT with some more code.
import sys,os
disk = file("/dev/disk5",'rb')
disk.seek(0)
sector_size=512
first_sector = disk.read(1*sector_size)
fat_part_list = (first_sector[-66:])[:64]
part1=fat_part_list[:16]
#more code here in order to analyse the first partition information in the MBR and get the required offset to actually read the partition itself.
#now for instance lets say I want to write here in sector 1 byte 0 ( so basically at seek(0).
disk.close()#close the device
disk = file("/dev/disk5","r+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 16] Resource busy: '/dev/disk5'
in fact you could simply see the problem as this:
http://pastie.org/2521541
never got the formating to work properly...
it all seems like an privileges error, but running the interpreter with sudo yields no changes.

You should unmount the block device before opening it in Python.

Related

Why doesn't python show error at the first time and only show at the second time?

I'm trying to make a small function using python's os module to detect my android's storage and return True or False. I'm running on linux and this is my code and note that the reason I added print statements is to make sure everything is okey.
import os
def usb_detect(path):
for usb in os.listdir(path): # Before accessing usb storages, we have to access into mtp:host= blah
if not os.listdir(os.path.join(path,usb)): # Now we try to access the usb device and show it's storages
print(os.listdir(os.path.join(path,usb)))
return False
else:
print(os.listdir(os.path.join(path,usb)))
return True
print(usb_detect(path='/run/user/1000/gvfs/'))
I have tried these
When I connect my android with usb,set to File Transfer and run the first time, it shows a list containing my android's storage and True. When I set to No file transfer, it shows this error...
Traceback (most recent call last):
File "/home/yemankyaw/PycharmProjects/pythonProject/usb_access.py", line 24, in <module>
print(usb_detect(path='/run/user/1000/gvfs/'))
File "/home/yemankyaw/PycharmProjects/pythonProject/usb_access.py", line 16, in usb_detect
if not os.listdir(os.path.join(path,usb)): # Now we try to access the usb device and show it's storages
OSError: [Errno 5] Input/output error: '/run/user/1000/gvfs/mtp:host=Android_Android_86bb9bfe0005'
but when I run again without changing setting, the error is gone and the program shows empty list and False as expected.
In fact, runing the first time in either File Transfer Mode or No Transfer Mode won't show the error, but when I set to another mode and run the second time, it will show the error. Then if I run again without changing setting, the error is gone forever until I change mode.
I thought changing to another mode and running immediately might be the cause of error but I waited, it's not. Whenever I changed to another mode, it shows error.

Python Path.rglob failing on network error when encountering folder without permission

I am new to Python and have been using this site as a reference...thanks for everything, I have learned a ton. First question:
I am running a basic recursive file search with Path.rglob(). I am running into a error when it encounters a folder that it does not have permission to access. I am running Python 3.7 on Windows and connecting to a windows share on a network drive.
Here's my code:
scan_folder = pathlib.Path("//192.168.1.242/Media")
nfo_files = list(scan_folder.rglob("*.nfo"))
It works perfectly until I encounter a folder that I do not have permission to access, then it errors out with:
Traceback (most recent call last):
File "D:/Working/media_tools/media_tools/movies_nfo_cataloger.py", line 337, in <module>
nfo_files = list(scan_folder.rglob("*.nfo"))
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 1094, in rglob
for p in selector.select_from(self):
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 544, in _select_from
for p in successor_select(starting_point, is_dir, exists, scandir):
File "C:\Users\ulrick65\Anaconda3\lib\pathlib.py", line 507, in _select_from
entries = list(scandir(parent_path))
OSError: [WinError 59] An unexpected network error occurred: '\\\\192.168.1.242\\Media\\#recycle'
Process finished with exit code 1
I searched and found the following Issue for Pathlib that appears to have been fixed, however the error is different in my case as it points to "Unexpected network error" instead of permissions.
https://bugs.python.org/issue24120
I verified that this is indeed a permissions error, I do not have access to that Recycle folder as the user I am logged in as. I edited the permissions for that folder and gave myself access and the code runs fine after that.
I know I could use oswalk as it ignores these...but I figured given the bug fix I linked to above, so should path.glob however it doesn't. Also, using path.rglob() is pretty slick, one line of code and is fast (not that oswalk wouldn't be just as fast).
Any help is appreciated.

How do I easily and consistently cause an IOError of some sort when reading from or writing to a text file?

I'm teaching an intro programming class in Python, and we're talking about exceptions and file I/O. I'm looking for a way to quickly and simply test their error handling. Now it's easy to cause an IOError when opening a file (just make sure that there is no file with the given filename), but I'd like to be able to test whether or not they're able to handle IOErrors that crop up while reading from or writing to a file, and I can't think of a simple, quick way to ensure that an IOError will occur at that time. I tried using a binary file, which opens fine but causes trouble if you try to read from it, but that causes a UnicodeDecodeError, which is not a type of IOError in Python.
Any thoughts?
Insert some code that rebinds open() (and possibly file) at the beginning of the code to test:
>>> def open(path, *args, **kw):
... path = os.path.join("/some/path/that/dont/exist", path)
... return __builtins__.open(path, *args, **kw)
...
>>> open("foo.bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in open
IOError: [Errno 2] No such file or directory: '/some/path/that/dont/exist/foo.bar'

Handling errors while working with code snippets

I am running a bunch of code all at once in python by copying it from my editor and pasting it into python. This code includes nested for loops. I am doing some web scraping and the program quits at different times. I suspect that this is because it doesn't have time to load. I get the following error (once again - the program scrapes different amounts of text each time):
Traceback (most recent call last):
File "<stdin>", line 35, in <module>
IndexError: list index out of range
First, what does line 35 refer to? Is this the place in the relevant inner for-loop?
Second, I think that the error might be caused by a line of code using selenium like this:
driver.find_elements_by_class_name("button")[j-1].click()
In this case, how can handle this error? What is some example code with either explicit waits or exception handling that would address the issue?
It means that [j-1] doesn't exist for a given value of j, possibly if j-1 exceeds the max number of elements in the list
You can try your code and catch an IndexError exception like this:
try:
# your code here
except IndexError:
# handle the error here
An IndexError happens when you try to access an index of a list that does not exist. For example:
>>> a = [1, 2, 3]
>>> print(a[10])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
It's difficult to say how you should handle the error without more detail.
When working with code snippets, it's convenient to have them open in a text editor and either
only copy-paste into a console the part you're currently working on so that all the relevant variables are in the local namespace that you can explore from the console, or
copy-paste a moderate-to-large chunk as a whole while having enabled automatic post-mortem debugger calling, e.g. with Automatically start the debugger on an exception Activestate recipe or IPython's %pdb magic, or
run a script as a whole under debugger e.g with -m pdb, IPython's %run or by using an IDE.

Python 3.4 accessing stdout

Apologies for my ineptness. When I run the following in IDLE on my python 3.4 install it fails.
>>> sys.stdout.fileno()
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
sys.stdout.fileno()
io.UnsupportedOperation: fileno
This, seems to give something useful though...
>>> sys.stdout.fileno
<built-in method fileno of PseudoOutputFile object at 0x030927D0>
What obvious thing am I doing wrong?
thanks.
to cut a long story short I am actually trying to do this:
import os
os.write(1, "Hello world!\n")
But got the following error, so went down the route of trying out stdout
Traceback (most recent call last):
File "<pyshell#34>", line 1, in <module>
os.write(1, "Hello world!\n")
TypeError: 'str' does not support the buffer interface
and so the call to print sys.stdout.fileno() would give me the number, and I thought it might just be that it shouldn't be 1.
IDLE under windows is started with pythonw.exe, a console-less GUI. As such there is no stdout handle assigned, at all.
The shell window itself needs to redirect all stdout output to the GUI window, which is the PseudoOutputFile object you see.
If you wanted to experiment with writing to the 1 filenumber, you need to start IDLE with a console attached:
py -m idlelib
from a console should be enough to give you a process with an actual sys.__stdout__ file handle, and writing with os.write(1, ...) will work.
Do remember that writing directly to a file handle requires bytes, not Unicode text. Encode your text or use a b'...' bytes literal.

Categories

Resources