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

如何通过单条终端命令加载Python脚本并执行自定义代码?

加载Python脚本并在交互模式执行自定义代码的解决方案

问题背景

现有device.py脚本内容如下:

class Simulator():
    def run():
        print('Running...')

需要实现以下操作:

  • 在终端新标签页中打开
  • 将device.py加载到Python交互式控制台
  • 创建Simulator实例并调用run()方法,且不能修改device.py本身

尝试的命令如下,但-c指定的代码未执行:

SIMULATOR_DIR="$(pwd)/directory_to_script/"
gnome-terminal --working-directory=$SIMULATOR_DIR --tab -- bash -c "python -i device.py -c \"Simulator().run()\"" --title="Simulator (device)";

原因分析

Python的命令行参数处理规则是:-c参数必须放在脚本文件名之前,如果把-c放在脚本后面,它会被当作脚本的命令行参数,而非Python的执行命令,因此不会被Python解析执行。

解决方法

方法一:调整参数顺序,在-c中加载并执行

将-c放在脚本之前,在-c的代码里先加载脚本内容,再执行目标代码,同时保留交互模式:

SIMULATOR_DIR="$(pwd)/directory_to_script/"
gnome-terminal --working-directory="$SIMULATOR_DIR" --tab -- bash -c "python -i -c \"exec(open('device.py').read()); Simulator().run()\"" --title="Simulator (device)"

方法二:通过输入重定向拼接脚本与执行代码

利用bash的进程替换,把脚本内容和要执行的代码拼接后传给Python标准输入,同时开启交互模式:

SIMULATOR_DIR="$(pwd)/directory_to_script/"
gnome-terminal --working-directory="$SIMULATOR_DIR" --tab -- bash -c "python -i <(cat device.py && echo 'Simulator().run()')" --title="Simulator (device)"

方法三:使用模块导入规范实现

先将脚本所在目录加入Python路径,再导入模块执行代码,更符合Python的模块使用规范:

SIMULATOR_DIR="$(pwd)/directory_to_script/"
gnome-terminal --working-directory="$SIMULATOR_DIR" --tab -- bash -c "python -i -c \"import sys; sys.path.insert(0, '.'); from device import Simulator; Simulator().run()\"" --title="Simulator (device)"

效果说明

以上三种方法都能实现:打开终端新标签页,加载device.py后自动执行Simulator().run(),最后停留在Python交互式控制台中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 06:55:18