shar
shar

Reputation: 2088

sourcing a python script

Recently, I came across the Linux command source and then found this answer on what it does.

My understanding was that source executes the file that is passed to it, and it did work for a simple shell script. Then I tried using source on a Python script–but it did not work.

The Python script has a shebang (e.g. #!/usr/bin/python) and I am able to do a ./python.py, as the script has executable permission. If that is possible, source python.py should also be possible, right? The only difference is ./ executes in a new shell and source executes in the current shell. Why is it not working on a .py script? Am I missing something here?

Upvotes: 2

Views: 5797

Answers (2)

Mattie B
Mattie B

Reputation: 21309

You're still not quite on-target understanding what source does.

source does indeed execute commands from a file in the current shell process. It does this effectively as if you had typed them directly into your current shell.

The reason this is necessary is because when you run a shell script without sourcing it, it will spawn a subshell—a new process. When this process exits, any changes made within that script are lost as you return to the shell from which it spawned.

It follows, then, that you cannot source Python into a shell, because the Python interpreter is always a different process from your shell. Running a Python script spawns a brand-new process, and when that process exits, its state is lost.

Of course, if your shell is actually Python (which I would not recommend!), you can still "source" into it—by using import.

Upvotes: 7

SethMMorton
SethMMorton

Reputation: 48815

source executes the files and places whatever functions/aliases/environment variables created in that script within the shell that called it. It does this by not spawning a new process, but instead executing the script in the current process.

The shabang is used by the shell to indicate what to use to spawn the new process, so for source it is ignored, and the file is interpreted as the language of the current process (bash in this case). This is why using source on a python file failed for you.

Upvotes: 3

Related Questions