从代码中模拟命令行执行

Imitate command line execution from within code

我有一个 python 项目,打算通过 运行 从命令行执行 head 例程,即:

python ssd.py --train

但是,由于这是一个机器学习模型并且我没有 GPU,我想 运行 该项目完全在 Google Colab 中。这意味着我无法使用命令行启动文件(或者至少我不知道如何启动)。我选择的解决方法是使用单个笔记本作为 header 例程。

MWE-sketch(已编辑):

launcher.ipynb

!cp drive/MyDrive/.../ssd.py
from ssd import SSD
SSD("train")

ssd.py

...

__init__():
   # here is code that will
   # result in an error unless
   # the code below is executed first

...

# the code below is not inside any function
if __name__ == '__main__':
    # here is code that
    # must be executed first 

如果我在命令行中键入 python ssd.py --train,则首先执行 ssd.py 中的代码。如果我使用launcher.ipnyb,则先执行__init__()中的代码,导致错误。

我已经让它像这样工作了:

ssd.py

import sys as _sys

...

__init__():
   # here is the same code as before

...

def set_args(args):
    _sys.argv[1:] = args

def setup():
    # here is code that was previously
    # outside any function (i.e., right below)

# the code below is not inside any function
if __name__ == '__main__':
    setup()  

launcher.ipynb

!cp drive/MyDrive/.../ssd.py
import ssd
ssd.set_args(["--train"])
ssd.setup()

这似乎是一种过于复杂和原始的解决方案,但我想没有比这更好的解决方案了吗?