Danny Dan
Danny Dan

Reputation: 25

How to execute a command in python file?

Currently executing this in google colab:

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

How can I put the above command into a python file (executeNow.py), so that I'll be able to run this in google colab:

!python executeNow.py

Namely what should be written inside execute.py so that the above to commands will be equivalent?

Upvotes: 0

Views: 97

Answers (1)

Ngoc N. Tran
Ngoc N. Tran

Reputation: 1068

You can use the module subprocess for that. Put this in your executeNow.py:

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

However, for this task I'd recommend using a bash script: write this into executeNow.sh:

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

Optionally, make that file executable:

!chmod +x executeNow.sh

Then run this in Colab:

!sh executeNow.sh

If you did the optional part, you can contract the above command slightly shorter:

!./executeNow.sh

Upvotes: 1

Related Questions