如何执行 python 文件中的命令?

How to execute a command in python file?

目前正在 google colab 中执行:

!python myfile.py   --size 45  --file textfile.txt --data_folder somePath/folder

如何将上述命令放入 python 文件 (executeNow.py),以便我能够 运行 在 google colab 中执行此操作:

!python executeNow.py

即execute.py里面应该写什么,这样上面的命令就等价了?

您可以为此使用模块 subprocess。将其放入您的 executeNow.py:

import subprocess
subprocess.run(["python", "myfile.py", "--size", "45", "--file", "textfile.txt", "--data_folder", "somePath/folder"])

但是,对于此任务,我建议使用 bash 脚本:将其写入 executeNow.sh:

#!/bin/bash
python myfile.py --size 45 --file textfile.txt --data_folder somePath/folder

可选地,使该文件可执行:

!chmod +x executeNow.sh

然后 运行 在 Colab 中:

!sh executeNow.sh

如果你做了可选部分,你可以把上面的命令缩短一点:

!./executeNow.sh