python - 在 Python 解释器 : Explain behavior 中运行 Python 解释器

标签 python linux shell python-os

在 python 解释器(在 Linux 系统的 shell 中运行)中运行操作系统模块时,我注意到可以执行以下操作:

>>> os.system("python") #execute run python command in enclosing shell

产生以下输出,表示一个新的 python REPL session :

Python 2.7.9 (default, Apr  2 2015, 15:34:55) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> #*blinking cursor*

从这里,可以再次进行系统调用以启动新的 Python session ,从中我可以再次进行系统调用等。这些 Python 环境似乎彼此独立,因为变量不共享在 session 之间,并且系统调用被同等对待。

这些 session 似乎在彼此内部运行,至少在某种程度上,而不是并行运行,正如 quit() 函数的结果所证明的那样:

>>> os.system("python")
Python 2.7.9 (default, Apr  2 2015, 15:34:55) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> quit()
0
>>> quit()
0
>>> quit()
0
>>> quit()
shaked@shaked-ThinkPad-X220:~/Desktop$ python

然而,从 shell 快速检查(>>> os.system("ps -e"))正在进行的进程揭示了每个运行的 python 解释器的新 sh:

11802 ?        00:00:00 kworker/u16:0
11803 pts/3    00:00:00 sh
11804 pts/3    00:00:00 python
11806 pts/3    00:00:00 sh
11807 pts/3    00:00:00 python
11810 pts/3    00:00:00 sh
11811 pts/3    00:00:00 python
11813 pts/3    00:00:00 sh
11814 pts/3    00:00:00 ps

谁能从底层系统进程的角度解释这种(看似)奇怪的行为?也就是说,这些 session 是并行运行还是在彼此内部运行?

如果这个问题以前出现过,我深表歉意,但我不确定其他人是如何提出这个问题的。

最佳答案

当你使用os.system时,它performs the command in a subshell ,类似于 /bin/sh -c 'yourcommand'*。因此,你会得到你所描述的行为是完全明智的。这与运行没有什么不同:

/bin/sh -c 'python'

在任何 shell 中。

*在 Windows 上略有不同,请阅读文档。

关于python - 在 Python 解释器 : Explain behavior 中运行 Python 解释器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35042423/

相关文章:

python - Pyspark - 如何将 '4 hours' 多个窗口分组聚合

regex - 在一行中搜索多个字符串,中间有多个空格

android - 如何找出包中的 Activity 名称?安卓。亚行 shell

python - Numpy:创建 Python 对象的浅拷贝数组

python - 将 DateTimeindex 转换为仅包含年、小时和日而不包含时间信息

xml - 如何使用 sed 或任何其他 Unix 工具替换具有特定键值的 XML 文件中的所有值字段?

c - 为什么我在全新的套接字上收到 EPOLLHUP 事件

linux - 为什么在 Unix 的 crontab 条目中包含 ". ./.profile"?

在 shell 中重定向输入和输出的代码

python - "if x:"的弃用警告?