A unicode error with installing win_unc library - python

I am trying to install a win_unc library and I get the following error:
File "unc_credentials.py", line 36 """
Syntax error: (unicode error) 'unicodescape' codec can't decode bytes in position 340-341: truncated \uXXXX escape
and this is the code snippet from the unc_credentials.py that is causing the issue:
def __init__(self, username=None, password=None):
"""
Returns a new `UncCredentials` object. Both `username` and `password` are optional.
If neither are provided, the new object will mean that credentials are unnecessary.
`username` must be a string representing a Windows username (logon). Windows usernames
may include a domain prefix (i.e. "domain\username"). If `username` cannot be
construed as a valid Windows username, then this will raise an
`InvalidUsernameError`.
Note: UNC connections that require authentication will use the username of the
currently logged in Windows user unless specifically provided another
username.
Note: Providing `None` and `""` (the empty string) have very different meanings.
Usernames cannot be empty.
`password` must be a string representing a password.
Note: Providing `None` and `''` (the empty string) have very different meanings.
The empty string is a meaningful, legitimate password.
If only the first positional argument is provided and it is already an instance of the
`UncCredentials` class (either directly or by inheritance), this constructor will clone
it and create a new `UncCredentials` object with the same properties.
"""
the very last line with """" is line 36.
It looks like just a comment to me, but when I get rid of it I get another error no commands supplied
And it seems like there is an issue with the triple-double quotation marks on the last line, I may be wrong though.
I have tried playing around with different quotation marks and use 'r' in front of the strings, but I either get the same error or no commands supplied.
I would really appreciate any suggestions on how I can work around or fix this issue.

I no longer maintain this library. I cannot tell what's going on here but the only thing that comes to mind is the file was somehow corrupted during downloading or saving. If you open a HEX editor and inspect positions 340-341 as it suggests, you may find an odd non-ASCII character.
Please note that win_unc does not support systems using any language other than English.

I think, it is not necessary part of the script, just a comment. I've removed it and successful installed this module.

Related

Can't regex string between string and line break - str(x) versus x.decode()

Why does a regex fail of a string cast from an object when line breaks are present?
That is why does this fail to find a match (ie print 'Green') in a string created from str(obj):
import re
s = str(b'Package Name: Green\\r\\n Release version: 8.1\\r\\n')
match = re.search(r'Package Name: (.*)\r\n', s)
print(match.group(1))
When this succeeds using a string created from obj.decode()?
import re
s = (b'Package Name: Green\\r\\n Release version: 8.1\\r\\n').decode()
match = re.search(r'Package Name: (.*)\r\n', s)
print(match.group(1))
No matter what search pattern was tried, searching the string created by str(obj) failed to find a match...
The reason you get different results is that you’re doing different things. Calling str on a bytes with newline characters returns a string with a literal backslash and n; calling decode returns a string with a newline character in it. So, if you’re searching the results for newline characters, the second one will succeed, and the first will fail. And it’s the second one that you wanted.
In other words, using decode here is right, and str is wrong; that’s why you get different results. If you can’t think through the difference, try just printing them out: print(b.decode()); print(str(b)) and you’ll see the difference immediately.
In fact, you should usually be decoding the strings as soon as you receive them, and never looking at the bytes again. Then you never have to worry about the str representation of bytes objects (except maybe in some code that logs errors caused by invalid strings that you couldn’t decode). The only exception is when you know the bytes are some kind of encoded text, but can’t be sure what the encoding is. For example, if you’re parsing HTTP headers or email messages or Python source code, you don’t know the character set until you read part of the file and search it for special ASCII-encoded strings. Or, if you’re converting a bunch of old text files from Windows to Unix line endings and some are cp1252 while others are cp1250, you don’t care which is which because they both encode line endings the same way. For those cases, just stick with bytes, and search for b'\n' instead of '\n'.
If you want to know why Python makes this so complicated:
bytes objects are used to store strings encoded in your default encoding—but they’re also used to store strings encoded in different encodings, and binary data that isn’t a string at all. And a bytes object has no idea which of those it’s storing; they’re all just sequences of numbers.
Python 2 effectively assumed that a bytes was being used to store a string in your default encoding, so it let you convert back and forth to Unicode by calling functions like str, or even concatenating a bytes and Unicode string. That turned out to be one of the biggest sources of errors in the language. You still see Python 2 users posting questions here every few days asking why they got a UnicodeEncodeError when they weren’t calling encode anywhere (or, worse, when they were calling decode), and fixing that was one of the main reasons for Python 3’s existence.
The human-readable representation of a bytes object has to be something that can be produced without error, and read unambiguously, whether it’s a string in the default encoding, a string in a completely different encoding, or a sequence of pixel brightness values ranging from 0 to 255. The compromise solution (for things like that HTTP headers case above) is the backslash-escaped quoted string.
By the way, during the Python 2 to 3 transition, the core devs assumed multiple people would come up with clever EncodedBytes types that carried around their encoding, and could therefore act more like Python 2 byte strings but without all the associated errors, and after a couple years one of them would be the clear winner on PyPI and maybe they could add it to Python 3.3 or so. That’s what you’re probably instinctively reaching for here. But, as it turned out, nobody used any such libraries, because it’s almost always easier to just decode and encode at the edges of your program and use Unicode everywhere, and the exceptions are almost always cases where you don’t know the encoding so EncodedBytes wouldn’t help.
One last thing: thinking of functions like str or float as “casts” is misleading. While it looks superficially similar to the way you do explicit casts in C or Java or Go or whatever language you’re used to, it has a very different meaning

How to make a created file hidden? [duplicate]

Trying to hide folder without success. I've found this :
import ctypes
ctypes.windll.kernel32.SetFileAttributesW('G:\Dir\folder1', 2)
but it did not work for me. What am I doing wrong?
There are two things wrong with your code, both having to do with the folder name literal. The SetFileAttributesW() function requires a Unicode string argument. You can specify one of those by prefixing a string with the character u. Secondly, any literal backslash characters in the string will have to be doubled or you could [also] add an r prefix to it. A dual prefix is used in the code immediately below.
import ctypes
FILE_ATTRIBUTE_HIDDEN = 0x02
ret = ctypes.windll.kernel32.SetFileAttributesW(ur'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
if ret:
print('attribute set to Hidden')
else: # return code of zero indicates failure -- raise a Windows error
raise ctypes.WinError()
You can find Windows' system error codes here. To see the results of the attribute change in Explorer, make sure its "Show hidden files" option isn't enabled.
To illustrate what #Eryk Sun said in a comment about arranging for the conversion to Unicode from byte strings to happen automatically, you would need to perform the following assignment before calling the function to specify the proper conversion of its arguments. #Eryk Sun also has an explanation for why this isn't the default for pointers-to-strings in the W versions of the WinAPI functions -- see the comments.
ctypes.windll.kernel32.SetFileAttributesW.argtypes = (ctypes.c_wchar_p, ctypes.c_uint32)
Then, after doing that, the following will work (note that an r prefix is still required due to the backslashes):
ret = ctypes.windll.kernel32.SetFileAttributesW(r'G:\Dir\folder1',
FILE_ATTRIBUTE_HIDDEN)
Try this code:
import os
os.system("attrib +h " + "your file name")

Python Crypt Import Linux Salt

Having trouble getting the crypt to work for my Ubuntu salt. I can run it with an arbitrary salt but with the special salt it does not. Any help is appreciated.
This works:
cryptWord = crypt.crypt('word', "HX")
print cryptWord
#prints salted word
This does not:
zebra = crypt.crypt('password', "$1\$WDvKY5n\$")
print zebra
# prints None
I am trying to be able to compare the salted word to a slated password but am unable to with the more advanced salt. Any ideas?
This is an invalid salt.
Although the documentation doesn't say so, the source makes it clear that crypt.crypt will return None if the underlying C function returns NULL. POSIX allows it to do so, and linux/glibc explicitly does so when given an invalid salt.
So, what's wrong with this salt?
If you read the "Glibc notes" section on the manpage, the string $1\$WDvKY5n\$ is going to use 1\ as its encryption method id. There's an encryption method with id 1, but nothing with id 1\. Plus, the salt itself is WDvKY5n\, but the salt is only allowed to contain characters in the set [a-zA-Z0-9/].
Most likely, you printed out the salt in some way that caused the $ characters to be escaped (for the shell?), then copied and pasted the escaped version instead of the actual string.
If that's what went wrong, just use $1$WDvKY5n$ and everything will be fine.
If something else went wrong and the salt is irreversibly garbled, just go look it up correctly and use whatever you find.
Meanwhile, the reason this works for people on other platforms (returning '$1d2n7Q0.r54s' instead of None) is that BSD and FreeSec crypt (the stock implementations on most POSIX platforms besides linux) both take any salt that doesn't start with an underscore to be a traditional-crypt value, where the first two characters can be any ASCII value and the rest of the salt is just padding.

Net-SNMP returns HexString and then just String (Eclipse and Pydev)

I am doing an snmpget using Net-SNMP. Specifically I am sending a command via os.popen("etc"). The value returned is a Hex-string separated by spaces, something like this : "A0 f0 D0". The returned value comes sometimes in the form :"Hex-String: A0 f0 D0.." but sometimes comes in the form "String:\xA0\xf0\xD0" where, as you can see, the spaces are filled with "\x". Does anyone have an idea as to why this might be happening? I would prefer it if the returned value was the HEX-String with spaces, not \x.
I should note that I am using Eclipse with Pydev. I then ran the same code in pyscripter and got back my Hex-String value. I ran it again in Pyscripter and then the \x's returned. Is this something to do with an unclosed pipe?
I should also mention that the data I am getting back is bad in another sense. The Hex-String with spaces returns proper data values, but the String with \xs returns values that are not correct.
I have used Wireshark and it looks like the get request is exactly the same as one sent from the MIB. The MIB request returns the correct data, while the Eclipse request still returns bad data.
PyDev does one thing differently, which is setting: sys.setdefaultencoding(encoding) with the encoding of the java console (so that if you print unicode to the console it won't fail saying that the unicode doesn't decode as ascii). To see if this is your problem, you can go to eclipse\plugins\org.python.pydev\PySrc\pydev_sitecustomize\sitecustomize.py and comment the line which does: sys.setdefaultencoding(encoding)

How to fix unicode issue when using a web service with Python Suds

I am trying to work with the HORRIBLE web services at Commission Junction (CJ). I can get the client to connect and receive information from CJ, but their database seems to include a bunch of bad characters that cause a UnicideDecodeError.
Right now I am doing:
from suds.client import Client
wsdlLink = 'https://link-search.api.cj.com/wsdl/version2/linkSearchServiceV2.wsdl'
client = Client(wsdlLink)
result = client.service.searchLinks(developerKey='XXX', websiteId='XXX', promotionType='coupon')
This works fine until I hit a record that has something like 'CorpNet® 10% Off Any Service' then the ® causes it to break and I get
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 758: ordinal not in range(128)" error.
Is there a way to encode the ® on my end so that it does not break when SUDS reads in the result?
UPDATE:
To clarify, the ® is coming from the CJ database and is in their response. SO somehow I need to decode the non-ascii characters BEFORE SUDS deals with the response. I am not sure how (or if) this is done in SUDs.
Implicit UnicodeDecodeErrors is something you get when trying to add str and unicode objects. Python will then try to decode the str into unicode, but using the ASCII encoding. If your str then contains anything that is not ascii, you will get this error.
Your solution is the decode it manually like so:
thestring = thestring.decode('utf8')
Try, as much as possible, to decode any string that may contain non-ascii characters as soo as you are handed it from whatever module you get it from, in this case suds.
Then, if suds can't handle Unicode (which may be the case) make sure you encode it back just before handing the text back to suds (or any other library that breaks if you give it unicode).
That should solve things nicely. It may be a big change, as you need to move all your internal processing from str to unicode, but it's worth it. :)
The "registered" character is U+00AE and is encoded as "\xc2\xae" in UTF-8. It looks like you have a str object encoded in UTF-8 but some code is doing (probably by default) your_str_object.decode("ascii") which will fail with the error message you showed.
What you need to do is show us a complete example (i.e. ALL the code necessary to get the error), plus the full error message and traceback, so that at least we can guess whether the problem is in your code or in imported code.
I am using SUDS to interface with Salesforce via their SOAP API. I ran into the same situation until I followed #J.F.Sabastian's advice by not mixing str and unicode string types. For example, passing a SOQL string like this does work with SUDS 0.3.9:
qstr = u"select Id, FirstName, LastName from Contact where FirstName='%s' and LastName='%s'" % (u'Jorge', u'López')
I did not seem to need to do str.decode("utf-8") either.
If you're running your script from PyDev on Eclipse, you might want to go into Project => Properties and under Resource, set "Text File Encoding" to UTF-8, on my Mac, this defaults to "MacRoman". I suppose on Windoze, the default is either Cp1252 or ISO-8859-1 (Latin). You could also set this in your Workspace of your Projects inherit this setting from their workspace. This only effects the program source code.

Categories