如何使用相同的端口 运行 python 脚本

How to run python script with the same port

现在我正在 Gmail 中设置 oauth2 以从我的 python 脚本发送邮件。

我正在使用 Google 中的快速启动代码来验证授权代码,但我遇到的情况是,当我 运行 执行 python 脚本时,端口总是会发生变化.

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                '../credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

if __name__ == '__main__':
    main()

这段代码的问题是每当我 运行 脚本时,它总是会更改端口并且我无法在 google 控制台中设置重定向的 URI。

我的问题是如何在 python 脚本上设置 运行ning 端口?

比如下面的修改怎么样?

发件人:

creds = flow.run_local_server(port=0)

收件人:

creds = flow.run_local_server()
  • 在这种情况下,每次都使用端口8080

creds = flow.run_local_server(port=8000)
  • 在这种情况下,每次都使用端口8000

参考: