Copying a file with access locks, forcefully with python - python

I'm trying to copy an excel sheet with python, but I keep getting "access denied" error message. The file is closed and is not shared. It has macros though.
Is their anyway I can copy the file forcefully with python?
thanks.

If you do not have sufficient file permissions you will not be able to access the file. In that case you will have to execute your Python program as an user with sufficient permissions.
If on the other hand the file is locked using other means specific to Excel then I am not sure what exactly is the solution. You might have to work around the protection using other means which will require a fair amount of understanding of how Excel sheets are "locked". I don't know of any Python libraries that will do this for you.

Related

Can I insert a file in my standalone python program to be downloaded by users as a template file

I'm doing python coding self study and not a programmer.. this is my first entry here. Not sure if this is doable, (I have a very little knowledge about programming) but here it is.
Is it possible to insert a file, like a template, for the user to download in a standalone program? Tried searching online but have not been successful, maybe I just don't know how to term it.
Any suggestion is very welcome.. thanks in advance..
When user clicks 'Download template', they can download an Excel template
User can download the template that I inserted in a program, that is if inserting file in a standalone program is possible.
I think what you are asking is if you can embed a file into the .py itself (which is what I think you mean when you are saying standalone), to which the answer is no. It might be possible to compile the program into an exe using pyinstaller, but not sure how efficient or feasible that is.
If you really need this to be only one .py, I would suggest hosting it somewhere online for free and having python download the file from the url.
If I am being honest, the best way to go about doing this is to ditch the "standalone program" requirement and just shipping the template in a zip file with the .py file.
Edit: Creating the file on-demand
This slipped my mind as an idea (probably because it is the most involved and difficult way to do it), but you may be able to use something like XSLX writer to create the excel file on demand. Would require you to code a function that makes a brand new excel file from scratch, but this would not require downloads, zip files, or an executable, so it would be truly standalone (minus the added pip dependency).
Be warned though, I think python and XLSX can be finicky at times.

Restrict the Python file to read and write

I'm trying to restrict write and read access to a Python file. Suppose I have the following code:
with open('test.py', 'w+') as file:
file.write('''
open("document.txt", "w+").write("Hello, World!")
open("document.txt", "r+").read()
''')
By executing this code, a new file is created that in the new file there are two lines of code to write and read a another file.
I want the file created by executing this code (test.py) to hit PermissionError while running and not be able to create a new file or read it; Also, this file is only executable and normal commands work in it, but it can not access other files.
If I read you correctly, this is not a python problem, but an environment problem. I understand the question as something like 'how do I prevent python code from executing arbitrary reads or writes?'. There would be a trivial solution (modifying the generated test.py so it throws an error) but presumably that's not what you want.
The easiest way to make python hit a PermissionError... is to make sure it doesn't have permissions. So run your code as a user with extremely limited permissions---specifically no write permissions anywhere---or perhaps no default permissions at all, and use something like facls to grant permission to read specific files explicitly from a more priveleged sentinel process. (This assumes you are running Linux, but there are likely other ways to do this in different OSs).
Alternatively, look into various sandboxing techniques to give you a python interpreter with the relavent modules replaced with modules which throw errors, or an environment where outside modification is impossible.
It would help if you made it clearer why this is important, and why you are writing a python script with another python script (is this just an example of malicious action?).
You could technically change the permission of the file itself on the filesystem your trying to access.
Check the previous thread about changing permissions
os.chmod(path, <permission value>)
Where 000 is to disable anyone other than root to edit on linux.

Python: Edit a xlsx file open by another user

I looked at google for a solution based on python, but did not find any...
My python script is trying to edit an xlsx that might be opened by another user from MS excel.
If I try to overwrite the .xlsx file or the ~$*.xlsx file, I get a winError 32:
'process cannot access the file because it is being used by another process'
My problem is that users around me use MS excel to look at this output... And MS excel always lock the files that are open, by default.
It there a way to 'steal' the access from the other users. (As they are not editing it anyway).
I cannot not change the user permission (I think) as I am not admin of the files.
I am using windows 10.
Thanks for your advices.
cheers.
There really is no way around this - it is Excel preventing any other process on the system from obtaining write access.
If it were running on the same machine, you could consider connecting to the running Excel instance and getting it to close and reopen the document after opening it for writing yourself, but in your example it would likely be opened by someone on another machine.
The only solution here is to instruct your users to open the worksheet as read-only, which is an option every version of Excel allows, in which case you might be able to open it for writing. Whether that will allow you to update it while they are looking at it, is doubtful - you likely may want to look into connecting to an Excel sheet on OneDrive or SharePoint (or Teams etc. that use SharePoint as a back-end).

Reading a windows file without preventing another process from writing to it

I have a file that I want to read. The file may at any time be overwritten by another process. I do not want to block that writing. I am prepared to manage corruption to the data that I read, but do not want my reading to be in any way change the behaviour of the writing process.
The process that is writing the file is a delphi program running locally on the server. It opens the file using fmCreate. fmCreate tries to open the file exclusively and fails if there are any other handles on the file.
I am reading the file from a python script that accesses the file remotely across our network.
I am interested in whether there is a solution, independent of whether it is supported by python or delphi. I want to know if there is any way of achieving this under windows without modifying the writing program.
Edit: To reiterate, this is not a duplicate. The other question was trying to get read access to a file that is being written to. I want to the writer to have access to a file that I have open for reading. These are different questions (although I fear the answer will be similar, that it can't be done.)
I think the real answer here, all of these years later, is to use opportunistic locks. With this, you can open the file for read access, while telling the OS that you want to be notified if another program wants to access the file. Basically, you can use the file as long as you like, and then back off if someone else needs it. This avoids the sharing/access violation that the other program would normally get, if you had just opened the file "normally".
There is an MSDN article on Opportunistic Locks. Raymond Chen also has a blog article about this, complete with sample code: Using opportunistic locks to get out of the way if somebody wants the file
The key is calling the DeviceIoControl function, with the FSCTL_REQUEST_OPLOCK flag, and passing it the handle to an event that you previously created by calling CreateEvent.
It should be straightforward to use this from Delphi, since it supports calling Windows API functions. I am not so sure about Python. But, given the arrangement in the question, it should not be necessary to modify the Python code. Just make your Delphi code use the opportunistic lock when it opens the file, and let it get out of the way when the Python script needs the file.
Also much easier and lighter weight than a filter driver or the Volume Shadow Copy service.
You can setup a filter driver which can act in two ways: (1) modify the flags when the file is opened, and (2) it can capture the data when it's written to the file and save a copy of the data elsewhere.
This approach is much more lightweight and efficient than volume shadow copy service, mentioned in comments, however it requires having a filter driver. There exist several drivers on the market (i.e. those are products which include a driver and let you write business logic in user mode) yet they are costly and can be an overkill in your case. Still, if you need the thing for private use only, contact me privately for a license for our CallbackFilter.
Update: if you want to let the writer open the file which has been already opened, then a filter which will modify flags when the file is being opened is your only option.

Prevent a file from being opened

I am writing a Python logger script which writes to a CSV file in the following manner:
Open the file
Append data
Close the file (I think this is necessary to save the changes, to be safe after every logging routine.)
PROBLEM:
The file is very much accessible through Windows Explorer (I'm using XP). If the file is opened in Excel, access to it is locked by Excel. When the script tries to append data, obviously it fails, then it aborts altogether.
OBJECTIVE:
Is there a way to lock a file using Python so that any access to it remains exclusive to the script? Or perhaps my methodology is poor in the first place?
Rather than closing and reopening the file after each access, just flush its buffer:
theloggingfile.flush()
This way, you keep it open for writing in Python, which should lock the file from other programs opening it for writing. I think Excel will be able to open it as read-only while it's open in Python, but I can't check that without rebooting into Windows.
EDIT: I don't think you need the step below. .flush() should send it to the operating system, and if you try to look at it in another program, the OS should give it the cached version. Use os.fsync to force the OS to really write it to the hard drive, e.g. if you're concerned about sudden power failures.
os.fsync(theloggingfile.fileno())
As far as I know, Windows does not support file locking. In other words, applications that don't know about your file being locked can't be prevented from reading a file.
But the remaining question is: how can Excel accomplish this?
You might want to try to write to a temporary file first (one that Excel does not know about) and replace the original file by it lateron.

Categories