【问题标题】:Configparser How to Use a URL?Configparser 如何使用 URL?
【发布时间】:2023-01-09 00:51:05
【问题描述】:

我尝试创建一个 config.ini 文件,我插入了它并想读取它并将其写入变量中以进行卷曲并获取设备名称

Config.ini
[DEFAULT]
#only default infos DONT CHANGE
DevicenameDEFAULT = NameoftheDevice
TGtokenCurlDEFAULT = TokenUrlforCUrltoTelegram

[DeviceInfo]
#change here your settings
Devicename = miniforum1-titty
TGtokenCurl = https://api.telegram.org/botxxxxxxx&text=

并想将其与变量一起使用

Geraet =
TGtoken =

并在此代码中使用 TGtoken:

def CurlExeptionErrorAccours():
    sleep(2)
    subprocess.call(['curl',
    '-X',
    'POST',
    '-d',
    'flow_x',
    (TGtoken,'ExeptionErrorAccours_',Geraet)])
    #Time for Timestamps
    timenow = datetime.datetime.now()
    print("Curl ExeptionErrorAccours", timenow)
    sleep(1)
    pass

我的脚本(函数)如下所示:

import configparser

configini = configparser.ConfigParser()     
configini.read("scr\config\config.ini")
#show and print
Device_Name = configini.get('DeviceInfo', 'Devicename')
print(Device_Name)
TGtoken = Device_Name

是这样还是我应该使用

TGtoken = configini.get('DeviceInfo', 'Devicename')

【问题讨论】:

  • 顺便说一句,不要使用 subprocess + curl。使用像 urllib 这样的真正的 python http 客户端库
  • 我真的不明白你的问题。 TGtoken = Device_Name 是不必要的代码行
  • 所以这样更好:TGtoken = configini.get('DeviceInfo','TGtokenCurl')
  • 只要您始终如一地使用变量名称,它们并不重要。那是一个 url,不是一个 token,所以我建议你不要给它起一个 TGtoken 的名字。
  • 为什么我应该使用 urllib?我从其他脚本中复制了代码并使用它,所以我已经用过了。你有 urllib 的教程吗?

标签: python configparser


【解决方案1】:

Configparser 只使用字符串。 URL 只是一个字符串。

您似乎只是在询问变量。所以,首先我建议你使用参数

def CurlExeptionErrorAccours(url, Geraet):
    subprocess.call(['curl',  # however, you should replace this with native python http client call 
    '-X',
    'POST',
    '-d',
    'flow_x',
    (url,'ExeptionErrorAccours_',Geraet)])
    # TODO: you should check the exit code of this command for failures 

然后

import configparser

configini = configparser.ConfigParser()     
configini.read("scrconfigconfig.ini")
#show and print
url = configini.get('DeviceInfo', 'TGtokenCurl')
Geraet = configini.get('DeviceInfo', 'Devicename') # German translation? Why not put Geraet as config key? 
CurlExeptionErrorAccours(url, Geraet)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多