%%writefile 魔术命令在常规 Python

%%writefile magic command in regular Python

我正在从终端将 Python 代码从 Jupyter Notebook 复制到 .py 文件到 运行。 我找不到如何实施这条线的方法:

%%writefile -a submission.py

常规 Python 中与 %%writefile 魔法命令相同的代码是什么?

替换为:

%%writefile -a submission.py

    model = Net()
    model = model.float()
    model.load_state_dict(state_dict)
    model = model.to('cpu')
    model = model.eval()
    obs = tensor(obs['board']).reshape(1, 1, config.rows, config.columns).float()
    obs = obs / 2
    action = model(obs)
    return int(action)

通过这个:

submission_ending = '''    model = Net()
    model = model.float()
    model.load_state_dict(state_dict)
    model = model.to('cpu')
    model = model.eval()
    obs = tensor(obs['board']).reshape(1, 1, config.rows, config.columns).float()
    obs = obs / 2
    action = model(obs)
    return int(action)'''

with open('submission.py', mode='a') as file:
    file.write(submission_ending)