windows中的python调用linux子系统的命令行 出现的问题

285 阅读2分钟

问题说明

在windows里通过wsl安装了ubuntu系统,在ubuntu系统内装了某一个工具,例如iverilog,在ubuntu终端内,是可以正确使用的,而在windows中通过python脚本调用却报错,说没有该命令

# encoding=utf-8
import subprocess

# 指定要使用的 WSL 发行版
distro_name = "Ubuntu-24.04"  # 确保使用正确的发行版名称

# 定义要在指定发行版中运行的命令
command = "iverilog -V"

try:
    # 使用 subprocess 在指定发行版中运行命令
    result = subprocess.run(['wsl', '-d', distro_name, "bash", "-c", command], capture_output=True, text=True,
                            encoding='utf-8',
                            errors='ignore')

    # 打印命令输出
    print("stdout:", result.stdout)
    # print("stderr:", result.stderr)

    # 检查命令是否成功
    if result.returncode == 0:
        print("Command executed successfully")
    else:
        print("Command failed with return code", result.returncode)
except UnicodeDecodeError as e:
    print("Error decoding output:", e)

原因和解决方案

以下内容全部由chatgpt生成,本人验证过方法2是可以的,其他方法应该也可以

那么可能的问题在于 WSL 调用的配置或环境变量的问题。以下是详细的调试和解决方法:

方法 1:使用绝对路径

尝试使用 iverilog 的绝对路径。如果 iverilog 安装在标准路径中,通常位于 /usr/bin/iverilog

  1. 首先,在 WSL 终端中找到 iverilog 的绝对路径:

    sh
    复制代码
    which iverilog
    

    假设输出是 /usr/bin/iverilog

  2. 在 Python 脚本中使用绝对路径:

    python
    复制代码
    import subprocess
    
    # 指定要使用的 WSL 发行版
    distro_name = "Ubuntu-20.04"
    
    # 定义要在指定发行版中运行的命令,使用绝对路径
    command = "/usr/bin/iverilog -V"
    
    try:
        # 使用 subprocess 在指定发行版中运行命令
        result = subprocess.run(['wsl', '-d', distro_name, command], capture_output=True, text=True, encoding='utf-8', errors='ignore')
        
        # 打印命令输出
        print("stdout:", result.stdout)
        print("stderr:", result.stderr)
        
        # 检查命令是否成功
        if result.returncode == 0:
            print("Command executed successfully")
        else:
            print("Command failed with return code", result.returncode)
    except UnicodeDecodeError as e:
        print("Error decoding output:", e)
    

方法 2:使用 Bash Shell 运行命令

有时通过直接调用 bash -c 可以解决路径和环境变量的问题:

python
复制代码
import subprocess

# 指定要使用的 WSL 发行版
distro_name = "Ubuntu-20.04"

# 定义要在指定发行版中运行的命令
command = "iverilog -V"

try:
    # 使用 subprocess 在指定发行版中运行命令,使用 bash -c
    result = subprocess.run(['wsl', '-d', distro_name, 'bash', '-c', command], capture_output=True, text=True, encoding='utf-8', errors='ignore')
    
    # 打印命令输出
    print("stdout:", result.stdout)
    print("stderr:", result.stderr)
    
    # 检查命令是否成功
    if result.returncode == 0:
        print("Command executed successfully")
    else:
        print("Command failed with return code", result.returncode)
except UnicodeDecodeError as e:
    print("Error decoding output:", e)

方法 3:设置环境变量

确保 PATH 环境变量在运行命令时正确设置。你可以在 WSL 中的 .bashrc.profile 文件中添加 iverilog 的路径:

  1. 打开 WSL 终端并编辑 .bashrc.profile

    sh
    复制代码
    nano ~/.bashrc
    
  2. 添加以下内容:

    sh
    复制代码
    export PATH=$PATH:/usr/bin
    
  3. 保存并退出后,重新加载配置:

    sh
    复制代码
    source ~/.bashrc
    

然后再尝试运行你的 Python 脚本。