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

PySimpleGUI中无法运行Shell命令/脚本的问题排查求助

问题分析与解决方案

从你的报错信息和代码来看,问题主要集中在脚本格式错误、执行权限不足以及环境变量路径缺失这三个方面,下面一步步帮你拆解解决:

1. 先解决--: command not found错误

这个报错是因为你的.txt脚本里用了--作为注释符号,但shell脚本默认只认#作为注释标记。打开你的myScript_am-ir.txt,把所有以--开头的行改成以#开头:

比如原脚本里的:

-- 这是一行注释

改成:

# 这是一行注释

2. 给脚本添加执行权限

macOS下默认下载或创建的文件没有可执行权限,在终端里运行以下命令给脚本授权:

chmod +x /Users/mu234/Desktop/myScript_am-ir.txt

3. 解决avrdude: command not found错误

这个问题是因为subprocess运行时的环境变量PATH和你终端里的不一样,导致系统找不到avrdude的位置,有两种解决方式:

方法一:用avrdude的绝对路径执行

先在终端里运行which avrdude,得到它的绝对路径(比如/usr/local/bin/avrdude),然后把脚本里所有的avrdude替换成这个完整路径。

方法二:在Python代码中传递完整环境变量

修改你的runCommand函数,让subprocess使用和终端一致的环境变量:

def runCommand(cmd, timeout=None, window=None):
    import os
    nop = None
    """
    run shell command
    @param cmd: command to execute
    @param timeout: timeout for command execution
    @param window: the PySimpleGUI window that the output is going to (needed to do refresh on)
    @return: (return code from command, command output)
    """
    # 用bash解释执行脚本,避免shebang缺失问题
    cmd = f'bash "{cmd}"'
    # 复制当前系统的环境变量,确保包含avrdude的路径
    env = os.environ.copy()
    # 可选:如果知道avrdude的路径,也可以手动追加到PATH里
    # env['PATH'] += ':/usr/local/bin'
    
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line + '\n'  # 加换行符让输出更易读
        print(line)
        window.refresh() if window else nop
    retval = p.wait(timeout)
    return (retval, output)

额外调试技巧

如果还是有问题,可以在runCommand函数开头添加一行代码,打印当前的PATH环境变量,确认avrdude的路径是否在其中:

print(f"当前PATH: {os.environ.get('PATH')}")
window.refresh()

按照上面的步骤修改后,你的脚本应该就能正常执行avrdude命令了。

内容的提问来源于stack exchange,提问作者Somene From EU

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:28:10