I'm coding in python, using version 2.6, working with the Uber API, and when I try to import the library uber_rides.auth it throws this error:
Traceback (most recent call last):
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\socket.py", line 4, in <module>
from uber_rides.auth import AuthorizationCodeGrant
File "C:\Inetpub\vhosts\underdevelopment.biz\httpdocs\web\webtemp3\uber\uber_rides\auth.py", line 133
query_params = [qp: query_params[qp][0] for qp in query_params]
^
SyntaxError: invalid syntax
The original code of my script is this:
print('Content-Type: text/plain')
print('')
from uber_rides.auth import AuthorizationCodeGrant
def main():
auth_flow = AuthorizationCodeGrant(
'xxxxxx-xxxxxxx',
'xxxxx-xxxxx',
'xxx-xxxxxxxxx',
'',
)
auth_url = auth_flow.get_authorization_url()
if __name__ == "__main__":
main()
It seems the error is from the library but I can't find it yet.
Yes, that's invalid Python syntax. However, it is not clear how you ended up with that file.
Someone or something altered that file. That's not the original source code as distributed by Uber, where that line uses the correct syntax for a dictionary comprehension:
query_params = {qp: query_params[qp][0] for qp in query_params}
Re-install the project, the error is not there upstream.
Note that the above syntax is only available in Python 2.7 and up. You could try to replace it with a dict() call with a generator expression, see Alternative to dict comprehension prior to Python 2.7:
query_params = dict((qp, query_params[qp][0]) for qp in query_params)
Take into account that there may be other issues with the code, upgrading to Python 2.7 is probably the better option.
Related
I need to get a list of all albums of my YouTube Music uploads library with ytmusicapi and I never work with Python before. I created the headers_auth.json and a test.py file with the following code from the example:
from ytmusicapi import YTMusic
ytmusic = YTMusic('headers_auth.json')
playlistId = ytmusic.create_playlist("test", "test description")
search_results = ytmusic.search("Oasis Wonderwall")
ytmusic.add_playlist_items(playlistId, [search_results[0]['videoId']])
I ran from the Ubuntu terminal: python /home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py
Result error:
Traceback (most recent call last): File
"/home/do/Desktop/ytmusicapi/ytmusicapi-master/test.py", line 1, in
from ytmusicapi import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/init.py",
line 2, in
from ytmusicapi.ytmusic import YTMusic File "/home/do/Desktop/ytmusicapi/ytmusicapi-master/ytmusicapi/ytmusic.py",
line 28
auth: str = None,
^ SyntaxError: invalid syntax
How to fix that?
This is because you are using a different version of Python.
The library you are using requires Python>=3.5 wheraas you seem to be using Python2.
If you are curious this code
def f(x:int):
return
is valid in Python3.5+ versions but not in Python2.
You will have to either switch to Python3 to use that library or else you can clone the repo and convert the whole repo to Python2 using something like this(though there might be other ways too).
I'd recommend you simply switch to Python3.5 or higher.
I create config.py file and run my Python code and it shows syntax error.
#config.py
API_key = GTW89NF3
mac = mac=6c:rf:7f:2b:0e:g8
File "flaskapp.py", line 8, in <module>
from config import API_KEY
File "/home/ubuntu/flaskapp/config.py", line 4
mac = mac=6c:rf:7f:2b:0e:g8
^
SyntaxError: invalid syntax
Why do you write mac = 2 times ?
Try going with one of these depending on what you want to achieve:
mac = "6c:rf:7f:2b:0e:g8"
Or
mac = "mac=6c:rf:7f:2b:0e:g8"
a config.py file usually has to be syntactically valid Python.
In Python, values that are strings need quotes around them:
API_KEY = "GTW89NF3"
mac = "6c:rf:7f:2b:0e:g8"
Also, it looks like the Flask app that you are using uses a config item called API_KEY, not API_key; generally Python is case sensitive.
I am trying to create python classes to be used in Excel, taking references from Python: Programming on Win32.
Currently:
Python script (win32comLibrary.py)
class PythonUtilities:
_public_methods_ = [ "SplitString" ]
_reg_progid_ = "PythonDemos.Utilities"
_reg_clsid_ = "{AF272547-D5BC-4452-852E-3F8746672097}"
def SplitString(self, val, item = None):
import string
if item!=None: item = str(item)
return string.split(str(val), item)
if __name__== "__main__":
print("Registering COM server...")
import win32com.server.register
win32com.server.register.UseCommandLine(PythonUtilities)
Excel VBA
Sub test()
Set PythonUtils = CreateObject("PythonDemos.Utilities")
response = PythonUtils.SplitString("Hello From VB", " ")
For Each Item In response
MsgBox Item
Next Item
End Sub
Questions:
(a) at the reponse = ... line, there is a runtime error '-2147467259 (80004005)': Unexpected Python Error: Traceback (most recent call last): File .....
(b) when i typed python win32comLibrary.py --unregister in cmd, it returned Registering COM server...Traceback (most recent call last): File "win32comLibrary.py", line 19, in (module) import win32com.server.register ImportError: No module named win32com.server.register
I am currently using anaconda (spyder) and have installed pywin32. Invoking win32com.client methods from Python don't seem to throw any error.
Any assistance would be appreciated.
I have managed to solve the issue - just to close this off. Not sure if its the difference between older versions of python and 3.x but string.split(str(val), item) doesn't seem to work anymore. Instead, I have changed the return statement to return val.split(item). Oversight on my part - apologies.
I've created a standalone exe Windows service written in Python and built with pyInstaller. When I try to import wmi, an exception is thrown.
What's really baffling is that I can do it without a problem if running the code in a foreground exe, or a foreground python script, or a python script running as a background service via pythonservice.exe!
Why does it fail under this special circumstance of running as a service exe?
import wmi
Produces this error for me:
com_error: (-2147221020, 'Invalid syntax', None, None)
Here's the traceback:
Traceback (most recent call last):
File "<string>", line 43, in onRequest
File "C:\XXX\XXX\XXX.pyz", line 98, in XXX
File "C:\XXX\XXX\XXX.pyz", line 31, in XXX
File "C:\XXX\XXX\XXX.pyz", line 24, in XXX
File "C:\XXX\XXX\XXX.pyz", line 34, in XXX
File "C:\Program Files (x86)\PyInstaller-2.1\PyInstaller\loader\pyi_importers.py", line 270, in load_module
File "C:\XXX\XXX\out00-PYZ.pyz\wmi", line 157, in <module>
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 72, in GetObject
File "C:\XXX\XXX\out00-PYZ.pyz\win32com.client", line 87, in Moniker
wmi.py line 157 has a global call to GetObject:
obj = GetObject ("winmgmts:")
win32com\client__init.py__ contains GetObject(), which ends up calling Moniker():
def GetObject(Pathname = None, Class = None, clsctx = None):
"""
Mimic VB's GetObject() function.
ob = GetObject(Class = "ProgID") or GetObject(Class = clsid) will
connect to an already running instance of the COM object.
ob = GetObject(r"c:\blah\blah\foo.xls") (aka the COM moniker syntax)
will return a ready to use Python wrapping of the required COM object.
Note: You must specifiy one or the other of these arguments. I know
this isn't pretty, but it is what VB does. Blech. If you don't
I'll throw ValueError at you. :)
This will most likely throw pythoncom.com_error if anything fails.
"""
if clsctx is None:
clsctx = pythoncom.CLSCTX_ALL
if (Pathname is None and Class is None) or \
(Pathname is not None and Class is not None):
raise ValueError("You must specify a value for Pathname or Class, but not both.")
if Class is not None:
return GetActiveObject(Class, clsctx)
else:
return Moniker(Pathname, clsctx)
The first line in Moniker(), i.e. MkParseDisplayName() is where the exception is encountered:
def Moniker(Pathname, clsctx = pythoncom.CLSCTX_ALL):
"""
Python friendly version of GetObject's moniker functionality.
"""
moniker, i, bindCtx = pythoncom.MkParseDisplayName(Pathname)
dispatch = moniker.BindToObject(bindCtx, None, pythoncom.IID_IDispatch)
return __WrapDispatch(dispatch, Pathname, clsctx=clsctx)
Note: I tried using
pythoncom.CoInitialize()
which apparently solves this import problem within a thread, but that didn't work...
I also face the same issue and I figure out this issue finally,
import pythoncom and CoInitialize pythoncom.CoInitialize (). They import wmi
import pythoncom
pythoncom.CoInitialize ()
import wmi
I tried solving this countless ways. In the end, I threw in the towel and had to just find a different means of achieving the same goals I had with wmi.
Apparently that invalid syntax error is thrown when trying to create an object with an invalid "moniker name", which can simply mean the service, application, etc. doesn't exist on the system. Under this circumstance "winmgmts" just can't be found at all it seems! And yes, I tried numerous variations on that moniker with additional specs, and I tried running the service under a different user account, etc.
Honestly I didn't dig in order to understand why this occurs.
Anyway, the below imports solved my problem - which was occurring only when ran from a Flask instance:
import os
import pythoncom
pythoncom.CoInitialize()
from win32com.client import GetObject
import wmi
The error "com_error: (-2147221020, 'Invalid syntax', None, None)" is exactly what popped up in my case so I came here after a long time of searching the web and voila:
Under this circumstance "winmgmts" just can't be found at all it
seems!
This was the correct hint for because i had just a typo , used "winmgmt:" without trailing 's'. So invalid sythax refers to the first methods parameter, not the python code itself. o_0 Unfortunately I can't find any reference which objects we can get with win32com.client.GetObject()... So if anybody has a hint to which params are "allowed" / should work, please port it here. :-)
kind regards
ChrisPHL
I'm running python2.5 and trying to use the astLib library to analyse WCS information in astronomical images. I try and get the object instanciated with the following skeleton code:
from astLib import astWCS
w = astWCS.WCS('file.fits') # error here
where file.fits is a string pointing to a valid fits file.
I have tried using the alternate method of passing a pyfits header object and this fails also:
import pyfits
from astLib import astWCS
f = pyfits.open('file.fits')
header = f[0].header
f.close()
w = astWCS.WCS(header, mode='pyfits') # error here also
The error is this:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 79, in __init__
self.updateFromHeader()
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/astLib/astWCS.py", line 119, in updateFromHeader
self.WCSStructure=wcs.wcsinit(cardstring)
File "/home/astro/phrfbf/build/lib/python2.6/site-packages/PyWCSTools/wcs.py", line 70, in wcsinit
return _wcs.wcsinit(*args)
TypeError: in method 'wcsinit', argument 1 of type 'char *'
When I run in ipython, I get the full error here on the pastebin
I know the astWCS module is a wrapped version of WCStools but i'd prefer to use the Python module as the rest of my code is in Python
Can anyone help with this problem?
Just found out the updated version of this library has fixed the problem, thanks for everyone's help
Oh sorry, I should have seen. Looking at the pastebin in more detail, the only error I can think of is that, for some reason the header has unicode in it. It can't be converted to char *, and you get the error. I tried searching for something in the header, but everything looks okay. Can you do this and post the output in another pastebin?
import pyfits
f = pyfits.open('file.fits')
header = f[0].header
f.close()
for x, i in enumerate(header.iteritems()):
if len(str(i[1])) >= 70:
print x, str(i[1])
cardlist = header.ascardlist()
cardstring = ""
for card in cardlist:
cardstring = cardstring + str(card)
print repr(cardstring)
Or, if you can check the header of your fits file for "funny" characters, getting rid of them should solve the issue.