You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本在Linux VPS无法运行但Windows正常,求解决建议

问题排查与解决建议

1. 优先修复错误捕获,暴露真实问题

当前代码的except块会吞掉所有异常,只返回模糊提示,根本无法定位问题。修改为以下代码,把错误信息打印出来并返回给Discord:

try:
    # 原有的业务逻辑代码
except Exception as e:
    error_msg = f'An error occurred with your request: {str(e)}'
    print(f"Debug Error: {str(e)}") # 终端输出错误,方便调试
    await message.channel.send(error_msg)

2. 排查Windows与Linux的环境差异

  • Python版本:在VPS运行python --version,确保和Windows使用的Python版本一致(比如都是3.10+),如果是Python2,脚本开头的解释器路径改成#!/usr/bin/python3
  • 依赖包版本:运行pip list对比Windows和Linux上discord.py、requests的版本,版本差异可能导致兼容性问题。可以强制安装和Windows一致的版本:
    pip install discord.py==2.2.3 requests==2.28.2
    

3. 网络请求问题排查

  • 代理配置:如果不需要代理,直接删除proxies=PROXIES参数;如果需要代理,确认PROXIES里的地址是实际可用的,且Linux环境下代理无需额外认证(若需要认证,格式应为http://user:pass@proxy:port)
  • 请求头简化:当前请求头字段过多,部分字段(如sec-ch-ua-platform-version)可能与VPS实际系统不匹配,导致被目标网站拦截。简化为必要字段:
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
        'referer': 'https://www.goat.com/'
    }
    
  • API参数动态化:URL中的_dt=1679929318132是固定旧时间戳,目标网站可能会验证该参数。换成动态生成的当前时间戳:
    from datetime import datetime
    timestamp = int(datetime.now().timestamp() * 1000)
    url= f'https://ac.cnstrc.com/search/{query.replace(" ", "%20")}?c=ciojs-client-2.29.12&key=key_XT7bjdbvjgECO5d8&i=6ea2c248-7f53-49a6-8150-7cfa7950f77b&s=3&page=1&num_results_per_page=24&sort_by=relevance&sort_order=descending&fmt_options%5Bhidden_fields%5D=gp_lowest_price_cents_4&fmt_options%5Bhidden_fields%5D=gp_instant_ship_lowest_price_cents_4&fmt_options%5Bhidden_facets%5D=gp_lowest_price_cents_4&fmt_options%5Bhidden_facets%5D=gp_instant_ship_lowest_price_cents_4&_dt={timestamp}'
    
  • 响应状态检查:在search函数中添加响应状态码和内容打印,确认请求是否成功:
    def search(query):
        # 生成url的代码
        html = requests.get(url=url, headers=headers, proxies=PROXIES)
        print(f"Status Code: {html.status_code}")
        print(f"Response Preview: {html.text[:500]}")
        html.raise_for_status() # 主动抛出HTTP错误(如403、500)
        output = simplejson.loads(html.text)
        return output['response']['results'][0]
    

4. Discord配置与权限排查

  • CHANNEL_ID类型:代码中CHANNEL_ID是字符串,Discord要求必须是整数,修改为:
    CHANNEL_ID = 123456789012345678 # 替换为实际数字ID
    
  • Intents权限:登录Discord开发者后台,在对应机器人的“Privileged Gateway Intents”中开启Message Content Intent,否则机器人无法读取消息内容
  • Token有效性:确认TOKEN没有输入错误,Linux环境下若Token包含特殊字符,避免用单引号包裹(或正确转义)

5. Linux系统运行环境检查

  • 终端运行脚本:不要后台运行,直接在终端执行python3 your_script.py,实时查看所有print输出和错误信息
  • 网络连通性:用curl测试目标网站是否可访问:
    curl -I https://ac.cnstrc.com
    curl -I https://discord.com/api/v10/gateway
    
  • 日志记录:如果终端输出不方便查看,添加日志记录到文件:
    import logging
    logging.basicConfig(filename='bot.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
    # 替换print语句为logging.debug
    logging.debug(f"Fetched product: {product}")
    

内容的提问来源于stack exchange,提问作者user21495274

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:08:09