Python SyntaxError: invalid syntax - python

My python version is 3.4, below is the error message.
Traceback (most recent call last):
File "test.py", line 1, in <module
from avs_client import AlexaVoiceServiceClient
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/__init__.py", line 1, in <module
from avs_client.avs_client.client import AlexaVoiceServiceClient
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/avs_client/client.py", line 5, in <module
from avs_client.avs_client import authentication, connection, device, ping
File "/home/mstts/Documents/Amazon/alexa-voice-service-client/avs_client/avs_client/connection.py", line 64
**authentication_headers,
^
SyntaxError: invalid syntax
And below is code segment which raises the error.
headers = {
**authentication_headers,
'Content-Type': multipart_data.content_type
}
Thanks for anyone who could be as kind to let me know what I am doing wrong and why that would be great!

This additional unpacking syntax for dictionary literals was introduced in Python 3.5 (see PEP-448); in earlier versions, it’s a syntax error. If you cannot upgrade, you will have to create the headers in two steps, e.g.:
headers = {'Content-Type': multipart_data.content_type}
headers.update(**authentication_headers)
as suggested by Ozgur in the comments.

Related

fstring in JSON, ValueError: Invalid format specifier, Python

I have the following code:
import json
domain="abc.com"
rawlog = json.loads(
f'{"domain": ${domain}}')
print(rawlog["domain"])
Which gives me:
Traceback (most recent call last):
File "<string>", line 6, in <module>
ValueError: Invalid format specifier
>
The question is, what is the cause and if I can have fstring in Json? I'm using the newest Python: python3 --version shows Python 3.10.4.
I also tried:
import json
domain="abc.com"
rawlog = json.loads('{"domain": f'{domain}'}')
print(rawlog["domain"])
but it gives:
File "<string>", line 5
rawlog = json.loads('{"domain": f'domain'}')
^
SyntaxError: invalid syntax
As { and } have special meaning they need to be escaped to mean literal { and literal }, consider following simple example
import json
domain="abc.com"
string=f'{{"domain": "{domain}"}}'
parsed=json.loads(string)
print(parsed)
gives output
{'domain': 'abc.com'}

Python syntax error when trying to access path parameter in chalice

I am trying to access a path parameter using chalice but it's giving me a syntax error.
py file
#app.route('/someValue/{indicator}', methods=['GET']
def get_indicator_value(indicator):
Gives me this error mentioned below:
[ERROR] Runtime.UserCodeSyntaxError: Syntax error in module 'test': invalid syntax (test.py, line 74)
Traceback (most recent call last):
File "/var/task/test.py" Line 74
def some_value(indicator):
What am I missing here ?
In the first line, you are missing the ) at the end. This is the fixed code:
#app.route('/someValue/{indicator}', methods=['GET'])
def get_indicator_value(indicator):

os module broke python, getting errors for programs I'm not running [duplicate]

This question already has answers here:
Importing installed package from script with the same name raises "AttributeError: module has no attribute" or an ImportError or NameError
(2 answers)
Closed 7 months ago.
I am trying to parse JSON from Python. I recently started working with Python so I followed some stackoverflow tutorial how to parse JSON using Python and I came up with below code -
#!/usr/bin/python
import json
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
print j['script']
But whenever I run the above code, I always get this error -
Traceback (most recent call last):
File "json.py", line 2, in <module>
import json
File "/cygdrive/c/ZookPython/json.py", line 4, in <module>
j = json.loads('{"script":"#!/bin/bash echo Hello World"}')
AttributeError: 'module' object has no attribute 'loads'
Any thoughts what wrong I am doing here? I am running cygwin in windows and from there only I am running my python program. I am using Python 2.7.3
And is there any better and efficient way of parsing the JSON as well?
Update:-
Below code doesn't work if I remove the single quote since I am getting JSON string from some other method -
#!/usr/bin/python
import json
jsonStr = {"script":"#!/bin/bash echo Hello World"}
j = json.loads(jsonStr)
shell_script = j['script']
print shell_script
So before deserializing how to make sure, it has single quote as well?
This is the error I get -
Traceback (most recent call last):
File "jsontest.py", line 7, in <module>
j = json.loads(jsonStr)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
File "json.py", line 2, in <module>
import json
This line is a giveaway: you have named your script "json", but you are trying to import the builtin module called "json", since your script is in the current directory, it comes first in sys.path, and so that's the module that gets imported.
You need to rename your script to something else, preferrably not a standard python module.
It looks like you have a json.py module which is not part of the Standard Library. Not sure what ZookPython is. Try renaming ZookPython directory (or just json.py) and re-run.

Python 3 Unicode not found

I'm aware that unicode was changed to str in python 3 but I keep getting the same issue no matter how I write this code, can anyone tell me why?
I'm using boilerpipe for a specific set of webcrawls:
for urls in allUrls:
fileW = open('article('+ str(counter)+')', 'w')
articleDate = Article(urls)
articleDate.download()
articleDate.parse()
print(articleDate.publish_date)
fileW.write(str(Extractor(extractor='ArticleExtractor', url=urls).getText() + "\n\n\n" + str(articleDate.publish_date)+"\n\n\n"))
fileW.close
counter +=1
error:
Traceback (most recent call last):
File "/Users/Adrian/anaconda3/lib/python3.6/site-packages/boilerpipe/extract/__init__.py", line 45, in __init__
self.data = unicode(self.data, encoding)
NameError: name 'unicode' is not defined
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "webcrawl.py", line 26, in <module>
fileW.write(str(Extractor(extractor='ArticleExtractor', url=urls).getText() + "\n\n\n" + str(articleDate.publish_date)+"\n\n\n"))
File "/Users/Adrian/anaconda3/lib/python3.6/site-packages/boilerpipe/extract/__init__.py", line 47, in __init__
self.data = self.data.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
The error message is pointing to a line in boilerpipe/extract/__init__.py, which makes a call to the unicode built-in function.
I assume the link below is the source code for the package you are using. If so, it appears to be written for Python 2.7, which you can see if you look near the end of this file:
https://github.com/misja/python-boilerpipe/blob/master/setup.py
You have several options as far as I can see:
Find a Python 3 port of this package. There are at least a few out there (here's one and here's another).
Port the package to Python 3 yourself (if that is the only error, you could simply change that line to use str, but later changes could cause problems with other parts of the package). This official tool should be of assistance; this official guide should, as well.
Port you project to Python 2.7 and continue using the same package.
I hope this helps!

Python SocksiPy package error: TypeError: Type str doesn't support the buffer API for string?

When i try and connect to gmail through this code:
import socks
import imaplib
import socket
import socks
s = socks.socksocket()
s.setproxy(socks.PROXY_TYPE_HTTP, '192.168.208.51', 3128)
s.connect(('imap.gmail.com', 993))
I get the error message:
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
s.connect(('imap.gmail.com', 993))
File "C:\Python34\lib\site-packages\socks.py", line 406, in connect
self.__negotiatehttp(destpair[0],destpair[1])
File "C:\Python34\lib\site-packages\socks.py", line 357, in __negotiatehttp
while resp.find("\r\n\r\n")==-1:
TypeError: Type str doesn't support the buffer API
Any ideas? Im on a computer that uses a proxy hence using SocksiPy to connect to imap.gmail.com
There's nothing wrong with your code; you are using a version of SocksiPy that has not been ported to Python 3. You should upgrade to version 1.02. Or you should switch back to Python 2.
Explaination:
This is Python 3. Unlike Python 2, bytes and str objects are not interchangeable. If you try to do stuff like this:
>>> b'abc'.find('a')
You'll get the error you are seeing. In fact, the "buffer API" is the one implemented by bytes objects.

Categories