Python3.6运行Strava API示例代码时__future__与swagger_client报错求助
Let's break down how to resolve your two main issues: the print_statement SyntaxError and swagger_client compatibility problems.
1. Resolve the print_statement SyntaxError
The line from __future__ import print_statement is Python 2-specific—it was used to force Python 2 to treat print as a function instead of a statement. In Python 3, print() is already a built-in function by default, so this import is not only unnecessary but will throw an error.
Fix: Simply delete that line from your code entirely.
2. Fix swagger_client Compatibility Issues
If you're still seeing errors with swagger_client, it's likely because the auto-generated code from Strava's docs was written with Python 2 in mind. Here's how to fix this:
Step 1: Update or Reinstall the Swagger Client
First, ensure you have the latest Python 3-compatible version of the package:
pip uninstall swagger-client pip install --upgrade swagger-client
Step 2: Check for Remaining Python 2 Syntax
If you're using code downloaded directly from Strava's API docs, scan for other Python 2-specific syntax:
- Replace any
print "text"calls withprint("text")(add parentheses) - Replace
xrange()withrange()(Python 3 usesrange()for the efficient iterator thatxrange()was in Python 2) - Ensure string formatting uses Python 3-friendly methods (e.g.,
f"string {var}"or"string {}".format(var)instead of%formatting if you encounter issues)
Step 3: Generate a Fresh Python 3-Compatible Client
If the pre-built swagger-client still has issues, generate a custom client tailored for Python 3 using Swagger Codegen:
- Install Swagger Codegen (if you don't have it):
brew install swagger-codegen # For macOS # Or download the latest release from the Swagger Codegen GitHub repo - Generate the Python client from Strava's Swagger spec:
swagger-codegen generate -i https://developers.strava.com/swagger/swagger.json -l python -o strava-python-client - Install the generated client locally:
cd strava-python-client pip install .
Corrected Example Code Snippet
Here's what your code might look like after fixing the main issues:
import swagger_client from swagger_client.rest import ApiException from pprint import pprint # Configure OAuth2 access token for authorization: strava_oauth configuration = swagger_client.Configuration() configuration.access_token = 'YOUR_PERSONAL_ACCESS_TOKEN' # create an instance of the API class api_instance = swagger_client.ClubsApi(swagger_client.ApiClient(configuration)) id = YOUR_CLUB_ID # int | The identifier of the club. try: # Get Club api_response = api_instance.get_club(id) pprint(api_response) except ApiException as e: print("Exception when calling ClubsApi->get_club: %s\n" % e)
This should resolve both the SyntaxError and any swagger_client-related compatibility issues in Python 3.6.
内容的提问来源于stack exchange,提问作者runnerpaul

