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

问题描述

目前在 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