采购python脚本 [英] sourcing a python script

查看:44
本文介绍了采购python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我遇到了Linux命令 source ,然后找到了此答案.

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

我的理解是, source 执行传递给它的文件,并且它确实适用于简单的shell脚本.然后,我尝试在Python脚本上使用 source ,但没有用.

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.

Python脚本有一个shebang(例如,#!/usr/bin/python ),我能够执行 ./python.py 作为脚本具有可执行权限.如果可能的话, source python.py 也应该可行,对吧?唯一的区别是 ./在新的shell中执行,而 source 在当前的shell中执行.为什么在 .py 脚本上不起作用?我在这里想念什么吗?

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?

推荐答案

您仍然不太了解 source 的功能.

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

source 确实确实在当前Shell进程中执行了文件中的命令.就像您直接将它们直接输入到当前的shell中一样,它可以有效地执行此操作.

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.

之所以这样做是必要的,是因为当您运行shell脚本而不采购它时,它将生成一个子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.

然后,您将无法将Python导出到Shell中,因为Python解释器始终是与Shell不同的进程.运行Python脚本会产生一个全新的进程,当该进程退出时,其状态将丢失.

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.

当然,如果您的shell 实际上是Python(我不推荐使用!),您仍然可以使用 import 来获取"它.

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

这篇关于采购python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆