Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 505
shar Avatar asked Aug 27 '26 21:08

shar


1 Answers

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.

like image 113
zigg Avatar answered Aug 29 '26 12:08

zigg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!