0

I am trying to understand why a __main__.py file could be run from shell issuing python . within the folder where said file is located.

How does this work? What does the . stand for, and why is not the file name needed?

Where is the dot coming from?. Given a bash script, say

#!/bin/bash
#Dummy bash script
echo "This is a dummy bash script"

saved as dummy_bash_script. I could run it, opening a terminal from the folder where it is located, issuing

$ ./dummy_bash_script

providing hence an explicit path (./). Are the two dots related? Does the dot in python . indicate anything about the current directory? If yes, where is the backslash gone?

Another use for the . (dot) in bash is as a shortcut for source , but I fail to see any connection.

And why is not the file name needed, in python . ? I understand as a file is ran as a script "somewhere under the bonnet" it is assigned the name "main". That is, the special variable __name gets an assignment, __name__ = "__main__".

But how does this exactly work as a __main__ file is executed as script using the dot, i.e. how can this file be ran with python ., without file name?

Thanks

user37292
  • 248
  • 2
  • 12
  • The `.` always refers to the current folder. That's why `./script.sh` refers to a script in the current folder. Executing `.` will execute the current folder as a module (aka the `__main__.py` file in python) – mousetail Jan 17 '23 at 13:49
  • Short version: `__main__.py` is a special script that is run when the folder/package itself is run as a script, rather than being imported as a module, so `python .` is just saying "treat the current folder as the script to run". `__main__.py` doesn't mean anything to anything but Python though, so you can't use a similar trick without explicitly running `python`. But yes, the `.` in both cases means the same thing; the current directory. – ShadowRanger Jan 17 '23 at 13:51
  • The `.` shortcut in bash is different, referring to the current interpreter context. All the rest refer to the current context. Bash, unlike python, can't execute folders – mousetail Jan 17 '23 at 13:51
  • if you don't like `./` you can always add `.` to `PATH` in windows style but I strongly suggest not to. – Sam Vimes Jan 17 '23 at 15:09
  • Oh no actually I like it aplenty, just wanted to understand it, thanks – user37292 Jan 17 '23 at 16:04

0 Answers0