Nir
Nir

Reputation: 2629

executing python in bash

Running download-from-s3.py with python3 before the script name works but I would like to be able to run the file without it.

[nir test]$ ./test-download-from-s3.sh
../download-from-s3.py: line 2: import: command not found
../download-from-s3.py: line 3: import: command not found
[nir test]$ cat ./test-download-from-s3.sh
#!/bin/bash

. ../download-from-s3.py

I tried to put two different headers in download-from-s3.py, #!/usr/bin/env python3 and #!/usr/bin/python3. Neither worked.

Upvotes: 2

Views: 59

Answers (1)

CoderCharmander
CoderCharmander

Reputation: 1910

. is a shorter alias for source. source executes commands from a file in the current shell session. Just like you copy-pasted the python file into the script. Therefore, there's no point of selecting a different interpreter. It's really similar to #include in C/C++.

What you want is marking the file as executable (chmod +x), and then executing it just like it was a shell script:

./something.py

Note: don't use source/. for executing shell scripts either. This way, the executed script may accidentally redefine/override some of the variables or functions in the main program. Sourcing files is done when you explicitly want to import functions, read variables, etc.

Upvotes: 2

Related Questions