Python 'set' object does not support indexing - indexing

I am working on a Windows 7 os in a Python (3.2.2) shell. Trying to learn the language I entered and had returned the following:
>>> cast = {
'cleese',
'Palin',
'Jones',
'Idle'
}
>>> print (cast[1])
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print (cast[1])
TypeError: 'set' object does not support indexing
>>> cast.append('Gilliam')
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
cast.append('Gilliam')
AttributeError: 'set' object has no attribute 'append'
==========================
It seems as if the problem is not in the coding, but with how the program was installed.
I have installed, un-installed and installed again, but the resutl is the same. I there something I need to do before Python's shell is ready to be used?
hans

Python seems to work fine. The point is that set doesn't support indexing or appending. Try using a list instead ([] instead of {}). In place of appending, set has add, but indexing is out.
And Python has useful help,
>>> help(set)
prints a lot of info about sets.

It seems that you were trying to define a list. However, you used braces {} instead of brackets []. The interpreter treated it as a dictionary rather than a list, so indexing and append() didn't work here.

Just to mention in here, set's' do not support indexing, as they are hash based, it is very similar to dictionaries which don't support indexing as well. You can only access a dict by it's key.
If you need indexing, you can convert your set as follows:
convertedToList = list(set(1,2,3))

Related

Input seems to be expecting an integer instead of string

I'm new to working in terminal (Mac, bash) and starting a tutorial, but I don't get the results that are expected.
Here's my code in atom.
print('Hello, python')
name = input('What is your name? ')
print name
And here's what I get after entering Tim (or after entering anything other than and integer)
Hello, python
What is your name? Tim
Traceback (most recent call last):
File "max2.py", line 2, in <module>
name = input('What is your name? ')
File "<string>", line 1, in <module>
NameError: name 'Tim' is not defined
If I enter an integer it works fine.
Hello, python
What is your name? 4
4
My understanding is that input takes the user input and puts it in a string. Any help would be appreciated.
Your code is correct, but you are running it through the wrong version of Python. The input() function is different between Python 2 and Python 3.
Function
Python 2
Python 3
input()
Reads and evaluates a Python expression
Reads a string
raw_input()
Reads a string
Doesn't exist, use input()
Since Python 2 is practically obsolete, you should make sure that your script is being invoked through python3 and not through just "python" (which is different from OS to OS but usually means Python 2).
For example, if your script has a #! line (and you're running it via ./myscript.py) then change that line to specify "python3".
(However, I'm actually not sure whether macOS even comes with Python 3. You may need to install it through Homebrew or whatever else they use on macOS.)
Also note that the print syntax is also very different between the two. You're using the correct syntax for Python 3, but it is only by coincidence that print(x) with one parameter works the same way in both versions.

Error using pymtp and libmtp

I am new to programming on python and i am trying to create an application which uses pyMTP to communicate to an MTP device. However im getting this error and cant figure out the fix for it.
$ python c:/Users/Atul/Desktop/mtp.py
None
Traceback (most recent call last):
File "c:/Users/Atul/Desktop/mtp.py", line 2, in <module>
import pymtp
File "C:\Users\Atul\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pymtp.py", line 42, in <module>
_libmtp = ctypes.CDLL(_module_path)
File "C:\Users\Atul\AppData\Local\Programs\Python\Python36-32\lib\ctypes\__init__.py", line 348, in __init__
self._handle = _dlopen(self._name, mode)
TypeError: LoadLibrary() argument 1 must be str, not None
Think it is not a program, but a library, you have to import. Like once in python, import mtp (or import pymtp, i don't know anymore). Please be aware pymtp is about 5 years old and does only run on python 2. I have been working on a python 3 version but it's not really complete because i found testing MTP software is extremely time consuming because the mtp interface is very, very slow at startup. I suggest to look at gMTP to transfer you files.

How can I pass a 'unicode string' to os.environ within a wsgi.py

apache2
wsgi
VHOST
python3
If I try to set envvars as part of my wsgi.py I do run into problems if values contain non-ascii characters.
Traceback (most recent call last):
File "/home/vagrant/pyvenv/lib/python3.5/site-packages/absys/config/wsgi.py", line 13, in <module>
os.environ['DJANGO_TESTVAR'] = 'M\xc3\xb6\xc3\xb6\xc3\xb6\xc3\xb6'
File "/usr/lib/python3.5/os.py", line 730, in __setitem__
value = self.encodevalue(value)
File "/usr/lib/python3.5/os.py", line 799, in encode
return value.encode(encoding, 'surrogateescape')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-4: ordinal not in range(128)
When I try to do the same thing as a regular user or as root it works flawlessly. This seems to be due to the fact that os.environ does accept the passed unicode value ('Müüü') and does not try to encode it.
For a reason not understood the same does not seem to be true when run as part of wsgi.py
For a second I thought this question could provide an answer but setting LANG = de_DE.UTF-8in /etc/apache2/envvars did not change a thing.
I tried to read pretty much most of the resources around on django/wsgi/envvars and in particular Graham Dumpletons approach
but none of them seem to mention any encoding issues.
I guess, my question (governed by my understanding so far) boils down to:
"What governs os.environs encoding behaviour and how to influence it within the wsgi process?
If there is any additional information I can provide to aid finding an answer please let me know.
This answer is just a reiteration of Graham Dumpleton's most helpfull comment. All credit is his.
This problem most likely is the result of messed up locale setting in the wsgi-processes environment.
In case your mod_wsgi is run as its own dedicated deamon (as it most likely should) you can pass it the desired locale directly and hence avoid any issues due to how your distribution may handle apaches environment.
For this something along these lines should do the trick:
WSGIDaemonProcess my-django-site lang='en_US.UTF-8' locale='en_US.UTF-8'.
For a more elaborate explaination please read Grahams excellent blog post and refer to mod_wsgi's documentation.

Issues importing a custom toolbox within another custom tool

I'm trying to call on a custom python script within another script. Everything works fine if I run the script standalone outside of ArcGIS, but if I try to make it a custom tool with parameters, it gives me the following error:
Traceback (most recent call last):
File "C:\Users\jamil.harvich\Documents\ArcGIS\Python_Scripts\Working\IP_Anno\Script\Script_Part1.py", line 80, in <module>
arcpy.ConcatenateRowValues_AA(lyr[0] + '_Intersect', 'SHORT_DESC', 'NAME', lyr[2], '-')
File "C:\Users\jamil.harvich\Documents\ArcGIS\Python_Scripts\Working\IP_Anno\ConcatenateRowValues101.tbx", line 54, in ConcatenateRowValues
/jVXV+BHwwJ5+Gfgv/wnbP8A+NV2Eo+ZTjHPQ9qlR60cIvojBSkupxw+Avwvz/yTTwX/AOE7Z/8A
AttributeError: Object: Tool or environment <ConcatenateRowValues_AA> not found
Failed to execute (Script).
Thanks. I hope the question is clear. If you need me to specify anything, just ask.
Before calling it, in your script you should import the Toolbox that contains your tool "ConcatenateRowValues_AA", with the command:
arcpy.ImportToolbox(TOOLBOX_PATH)
where TOOLBOX_PATH is the absolute path to your .tbx file.

How to rewrite a specific frame in a traceback?

In python you can compile() string to be executed faster with exec(). But as soon as i use it, we lost information when an exception happen in the exec.
For example, here is a code snippet that calling a unknown method (for demo purposes):
code = 'my_unknown_method()'
bytecode = compile(code, '<string>', 'exec')
And later, i'm calling exec on that bytecode:
exec bytecode
The traceback showed is:
Traceback (most recent call last):
File "test.py", line 3, in <module>
exec bytecode
File "<string>", line 1, in <module>
NameError: name 'my_unknown_method' is not defined
The "exec()" frame is now obscure. I would like to have a better exception like:
Traceback (most recent call last):
File "test.py", line 3, in <module>
exec "my_unknown_method()"
File "<string>", line 1, in <module>
NameError: name 'my_unknown_method' is not defined
Any thoughts ?
Notes:
I don't want to use the second argument of compile (the filename)
I have tested to play with inspect and modify f_code on the frame, but it's readonly attribute.
EDIT: after looking more to sys.excepthook, i've seen that in python source code/traceback.c, when python want to show the line content, they are fopen() directly the file if found. No hook available at all to display our own content. The only way would be to create in real fake filename on disk ? Anyone ?
EDIT2: i checked some jinja2 debug code, and they are rewriting traceback too, but not for content. Would i need a custom except hook ? My concerns with it is since it's not in the traceback itself, if an user/module/whatever take the exception, the traceback will not contain valuable information.
You should have a look at this talk by Armin Ronacher. He's the author of Jinja2 and in this talk he explained, how he manipulates stack traces in Jinja2. If I remember correctly, he's using ctypes, to manipulate the data structures on the C level of Python. The talk was in my opinion the best talk of the whole Europython 2011 by the way.
After a deep search, it's not possible, CPython is using its own API to determine where the file is etc, and it cannot be patched in pure Python.
How about something like this:
import sys
def mkexec(code_str):
bc = compile(code, '<string>', 'exec')
def run():
try:
exec bc
except: # Yes I know a bare except
t, v, tb = sys.exc_info()
raise MyUsefullException("%s raised %s" % (code_str, v))
return run
exe = mkexec("some_unknown_something()")
exe()