0%

20230120-Python 綜合練習 (包含 LineNotify 陽春版)

Python 綜合練習 (包含 LineNotify 陽春版)

Python 陽春版

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import requests
import json
from urllib import parse

# 定義請求header
HEADERS = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Authorization': 'Bearer PW3rTdoziKQ9k7saM0QYvC5ghWD6oJKpMrbZL1N5jS8'}
# 定義請求地址
url = "https://notify-api.line.me/api/notify"
# 由字典方式定義請求body
FormData = {"message": 'message=測試訊息'}
# 字典轉換 k1=v1 & k2=v2 模式
data = parse.urlencode(FormData)
# 請求方式
content = requests.post(url=url, headers=HEADERS, data=data).text

print(content)

讀取設定檔

  • 程式
    1
    2
    3
    4
    5
    6
    7
    import json
    with open('appsettings.json', encoding='utf-8') as fh:
    config = json.load(fh)
    fh.close()
    del fh
    print(type(config['ChatGPT']))
    print(config['ChatGPT']['HttpRequestHeader']['Authorization'])
    設定檔
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    {
    "ChatGPT": {
    "Host": "https://api.openai.com/v1/completions",
    "Year": 2023,
    "HttpRequestHeader": {
    "ContentType": "application/json",
    "Authorization": "Bearer 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"
    },
    "Encoding": "utf-8"
    }
    }

取得 python 安裝路徑

1
2
3
4
5
import sys

locate_python = sys.exec_prefix

print(locate_python)

How to Find Where Python is Installed on Windows

結合工作排程器+寫log

1
2
3
4
5
6
7
8
9
10

# 取得現在時間
now = datetime.datetime.now()
txt = '上次更新時間為:' + str(now)

# 轉成df
df = pandas.DataFrame([txt], index=['UpdateTime'])

# 存出檔案
df.to_csv('log.csv', header=False)

使用windows排程器讓python自己動起來吧!只要簡單四步驟

  • 必須先執行的語法
    1
    pip install pytrends
  • 如果是在 Colab 則必須先執行
    1
    !pip install pytrends
  • 最終成果
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    import json
    import requests
    import json
    from urllib import parse
    import datetime
    import pandas

    #install pytrends
    #!pip install pytrends
    #import the libraries
    import pandas as pd
    from pytrends.request import TrendReq
    pytrend = TrendReq()
    # Get realtime Google Trends data
    df = pytrend.trending_searches(pn='taiwan')
    df.head(20)

    df[0]

    dict = df.to_dict()

    {k: str(v).encode("utf-8") for k,v in dict.items()}

    now = datetime.datetime.now()

    msg = '\n'
    msg = msg + '[' + str(now) + ']\n'

    for index, row in df.iterrows():
    msg=msg+row[0]+'\n'

    # print(msg)
    # print(datetime.datetime.now())

    content=""
    HEADERS = {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', 'Authorization': 'Bearer PW3rTdoziKQ9k7saM0QYvC5ghWD6oJKpMrbZL1N5jS8'}
    url = "https://notify-api.line.me/api/notify"
    FormData = {"message": msg}
    data = parse.urlencode(FormData)
    content = requests.post(url=url, headers=HEADERS, data=data).text


    txt = '上次更新時間為:' + str(now) + ' | 發送結果為: ' + content

    # 轉成df
    df = pandas.DataFrame([txt], index=['UpdateTime'])

    # 存出檔案
    df.to_csv('C:\\tmp\\PyTest\\log.csv', header=False)

    print(txt)
  • 工作排程器設定內容及執行結果
    • C:\tmp\PyTest\pyTest.py
    • C:\Users\hcc\AppData\Local\Programs\Python\Python37

Task Scheduler

  • 排程設定匯出
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    <?xml version="1.0" encoding="UTF-16"?>
    <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
    <RegistrationInfo>
    <Date>2023-01-20T03:04:35.3641273</Date>
    <Author>DESKTOP-VQ0VMS7\hcc</Author>
    <URI>\pyTrend</URI>
    </RegistrationInfo>
    <Triggers>
    <TimeTrigger>
    <Repetition>
    <Interval>PT5M</Interval>
    <StopAtDurationEnd>false</StopAtDurationEnd>
    </Repetition>
    <StartBoundary>2023-01-20T03:05:00</StartBoundary>
    <Enabled>true</Enabled>
    </TimeTrigger>
    </Triggers>
    <Principals>
    <Principal id="Author">
    <UserId>S-1-5-21-2083758626-828878104-4192247444-1001</UserId>
    <LogonType>Password</LogonType>
    <RunLevel>HighestAvailable</RunLevel>
    </Principal>
    </Principals>
    <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
    <StopOnIdleEnd>true</StopOnIdleEnd>
    <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
    </Settings>
    <Actions Context="Author">
    <Exec>
    <Command>python</Command>
    <Arguments>C:\tmp\PyTest\pyTest.py</Arguments>
    <WorkingDirectory>C:\Users\hcc\AppData\Local\Programs\Python\Python37</WorkingDirectory>
    </Exec>
    </Actions>
    </Task>