如何使用相同的端口运行python脚本 [英] How to run python script with the same port
问题描述
现在,我正在通过Gmail设置oauth2,以通过python脚本发送邮件.
Right now I am setting up oauth2 from Gmail to send mail from my python script.
我正在使用Google的快速入门代码来验证授权代码,但是我遇到的情况是,当我运行python脚本时,端口总是在变化.
I am using a quick start code from Google to verify the authorize code but I am facing a situation where the port always changes when I am running the python script.
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.
My problem with this code is that whenever I run the script, it always changes the port and I cannot set the redirected URI in google console.
我的问题是如何在python脚本上设置运行端口?
My question is that how can I set the running port on python script?
推荐答案
例如,如何进行以下修改?
For example, how about the following modification?
creds = flow.run_local_server(port=0)
收件人:
creds = flow.run_local_server()
- 在这种情况下,每次使用端口
8080
.
或
creds = flow.run_local_server(port=8000)
- 在这种情况下,每次使用端口
8000
.
这篇关于如何使用相同的端口运行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!