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

如何在WSL Ubuntu终端中连续执行命令运行非主目录Python脚本

解决WSL中通过subprocess切换目录并运行Python脚本的问题

你之前的写法subprocess.run(['wsl',"~","ls"])无法正确切换目录,原因是WSL不会单独解析~作为主目录,且这种参数格式无法让WSL执行多步命令。要实现先cd再运行脚本,有两种可靠方式:

方式一:通过WSL shell执行命令串

利用WSL的-c参数传递完整的shell命令,让shell处理目录切换和脚本执行:

import subprocess

# 替换为你的目标目录和脚本文件名
target_dir = "/home/your_user/non_home_dir"
script_name = "your_script.py"

# 用&&确保cd成功后再执行脚本
result = subprocess.run(
    ['wsl', '-c', f'cd {target_dir} && python3 {script_name}'],
    capture_output=True,
    text=True
)

# 查看执行结果
print("标准输出:")
print(result.stdout)
print("\n错误输出:")
print(result.stderr)

如果目标目录包含空格,记得给路径加双引号:

['wsl', '-c', 'cd "/path/with spaces" && python3 your_script.py']

方式二:直接指定脚本的完整路径

如果不想切换目录,也可以直接在WSL命令中使用脚本的绝对路径:

import subprocess

script_full_path = "/home/your_user/non_home_dir/your_script.py"
result = subprocess.run(
    ['wsl', 'python3', script_full_path],
    capture_output=True,
    text=True
)

print(result.stdout)

关键说明

  • wsl -c 是让WSL启动默认shell(通常是bash)来执行后续的命令串,这样cd、~这类shell语法才能被正确解析
  • 使用&&连接命令,可避免目录不存在时仍尝试运行脚本的情况

内容的提问来源于stack exchange,提问作者Gabe Paris-Moe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:12:13