【问题标题】:Python requests.text adding empty linesPython requests.text 添加空行
【发布时间】:2021-08-03 10:19:18
【问题描述】:

我正在尝试通过请求使用 GET 来获取我在 Github 上托管的项目的当前代码,以拥有某种自动更新系统,但是每当我获取最新的最新代码(原始 github 文件)时,它都会添加空白行在代码行之间,例如:

def clear():
    os.system('cls' if os.name =='nt' else 'clear')
clear()

变成

def clear():

    os.system('cls' if os.name =='nt' else 'clear')

clear()

当代码中没有它们时,它会在所有内容之间添加不必要的行。我的代码是:

import requests, time

ask = input('Would you like to update to the latest version of Switchence? ') # Switchence is the name of my app
if ask == 'y' or ask == 'yes':
    print('Ok, updating...')
    try:
        onlineVersion = requests.get('https://raw.githubusercontent.com/Aethese/Switchence/main/main.py')
        if onlineVersion.status_code != 200:
            print(f'[ERROR] status code is not 200, it is {onlineVersion.status_code} so the program will not update')
            time.sleep(5)
        else:
            onlineVersion = onlineVersion.text
            with open('autoupdate.py', 'w') as file: # autoupdate.py is my test file
                file.write(onlineVersion)
            print('Successfully updated to latest version! Rerun the program to use the newest version!')
        time.sleep(5)
    except Exception as error:
        print(f'Couldn\'t get latest latest update | {error}')
        time.sleep(5)
elif ask == 'n' or ask == 'no':
    print('Ok, you will not update to the latest version')
    time.sleep(5)
else:
    print('The only acceptable answers are Yes or No')
    time.sleep(5)

谁能帮助我或向我解释为什么我的代码不起作用?我正在运行最新的 pip 版本的请求。

【问题讨论】:

    标签: python-3.x python-requests


    【解决方案1】:

    以某种方式以二进制模式打开文件似乎可以解决问题:

    onlineVersion = onlineVersion.content
    with open('autoupdate.py', 'wb') as file: # autoupdate.py is my test file
        file.write(onlineVersion)
    

    这可能与Python inserts both a carriage return and a line feed after variable, instead of just line feed有关

    【讨论】:

    • 谢谢!这确实解决了我的问题,我不认为以二进制模式打开它会解决我的问题,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2013-01-19
    相关资源
    最近更新 更多