Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python script by shebang with `time` command

I have a python script, which I want to be able to run from bash.
This is simply solved by shebang.
The next step is to implement the time command into the shebang.
My best but not the complete successful idea was to use

#!/usr/bin/env -vS bash -c "time /usr/bin/python3 -OO"

which does so sadly not make python interpret the script file and ends in an interactive python session.

The output is

split -S:  ‘bash -c "time /usr/bin/python3 -OO"’
 into:    ‘bash’
     &    ‘-c’
     &    ‘time /usr/bin/python3 -OO’
executing: bash
   arg[0]= ‘bash’
   arg[1]= ‘-c’
   arg[2]= ‘time /usr/bin/python3 -OO’
   arg[3]= ‘./mypycheck.py’
Python 3.7.3 (default, Apr  3 2019, 05:39:12)

How can I do the job? Thanks in advance.

like image 461
Bastian Ebeling Avatar asked Jan 22 '26 07:01

Bastian Ebeling


2 Answers

At the end summing up all helpful details from here, I was able to reach my goal with the following solution.

  1. Installing time utiliy by running sudo apt install time
  2. Using the shebang #!/usr/bin/env -S /usr/bin/time /usr/bin/python3 -OO

And now all is running the way I was looking for.

like image 180
Bastian Ebeling Avatar answered Jan 24 '26 20:01

Bastian Ebeling


You can solve this by creating a secondary bash script, and just invoking it as the shebang.

Kamori@Kamori-PC:/tmp# ./timed.py
hello

real    0m0.028s
user    0m0.016s
sys     0m0.000s
Kamori@Kamori-PC:/tmp# cat timed.py
#!/bin/bash startup.sh

print("hello")
Kamori@Kamori-PC:/tmp# cat startup.sh
#!/usr/bin/env bash

time python3.7 timed.py
like image 26
Kamori Avatar answered Jan 24 '26 19:01

Kamori