标签归档:interpreter

如何在python解释器外壳中重复上一条命令?

问题:如何在python解释器外壳中重复上一条命令?

如何重复上一条命令?通常的键:向上,Ctrl +向上,Alt-p不起作用。他们产生荒谬的性格。

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 

How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don’t work. They produce nonsensical characters.

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 

回答 0

我使用以下命令在python shell上启用历史记录。

这是我的.pythonstartup文件。PYTHONSTARTUP环境变量设置为此文件路径。

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter

您将需要使模块readline rlcompleter启用此功能。

http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP上查看有关此信息。

所需模块:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html

I use the following to enable history on python shell.

This is my .pythonstartup file . PYTHONSTARTUP environment variable is set to this file path.

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter

You will need to have the modules readline, rlcompleter to enable this.

Check out the info on this at : http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP.

Modules required:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html

回答 1

在“ IDLE”中,转到“选项”->“配置IDLE”->“密钥”,然后选择“ history-next”和“ history-previous”来更改密钥。

然后单击“获取新的按键选择”,您就可以选择想要的任何按键组合。

In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys.

Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.


回答 2

Alt + p表示历史记录中的上一个命令,Alt + n表示历史记录中的下一个命令。

这是默认配置,您可以根据需要从选项->配置IDLE更改这些快捷键。

Alt + p for previous command from histroy, Alt + n for next command from history.

This is default configure, and you can change these key shortcut at your preference from Options -> Configure IDLE.


回答 3

您没有指定哪个环境。假设您正在使用IDLE。

从IDLE文档中:命令历史记录:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

You didn’t specify which environment. Assuming you are using IDLE.

From IDLE documentation: Command history:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

回答 4

ALT + p在Windows上的Enthought Python上对我有用。

ALT + p works for me on Enthought Python in Windows.


回答 5

Ctrl + p是向上箭头的常规替代方法。确保在Python版本中启用了gnu readline。

Ctrl+p is the normal alternative to the up arrow. Make sure you have gnu readline enabled in your Python build.


回答 6

在Ubuntu Server 12.04上,从源(Python3.4)安装了一个版本的Python之后,出现了这个问题。

这里的一些评论建议安装Ipython,我想提一下,即使使用Ipython,我的行为也相同。据我所知,这是一个readline问题。

为Ubuntu 12.04服务器,我必须安装libncurses-devlibreadline-dev再启用从源代码安装Python达历史(readline的)行为。我几乎是这样做的:

sudo apt-get install libncurses-dev libreadline-dev

之后,我删除了先前安装的Python(不是SYSTEM PYTHON,而是我从源代码安装的Python!),然后从源代码重新安装了它,一切正常。

我不必使用pip安装任何东西或编辑.pythonstartup。

On Ubuntu Server 12.04, I had this problem after installing a version of Python from source (Python3.4).

Some of the comments here recommend installing Ipython and I want to mention that I have the same behavior even with Ipython. From what I can tell, this is a readline problem.

For Ubuntu 12.04 server, I had to install libncurses-dev and libreadline-dev and then install Python from source for up-history (readline) behavior to be enabled. I pretty much did this:

sudo apt-get install libncurses-dev libreadline-dev

After that, I deleted the previously installed Python (NOT THE SYSTEM PYTHON, the one I had installed from source!) and reinstalled it from source and everything worked as expected.

I did not have to install anything with pip or edit .pythonstartup.


回答 7

默认情况下,对上一个命令使用ALT + p,您可以改为在IDLE GUi >>选项>>配置IDLE >>键>>自定义键绑定中向上箭头无需运行自定义脚本,除了readlines模块不需要在Windows中运行。希望能有所帮助。:)

By default use ALT+p for previous command, you can change to Up-Arrow instead in IDLE GUi >> OPtions >> Configure IDLE >>Key >>Custom Key Binding It is not necesary to run a custom script, besides readlines module doesnt run in Windows. Hope That Help. :)


回答 8

在CentOS上,我通过

yum install readline-devel

然后重新编译python 3.4。

在OpenSUSE上,我通过

pip3 install readline

引用此答案:https : //stackoverflow.com/a/26356378/2817654。也许“ pip3 install readline”是一个通用解决方案。尚未在我的CentOS上尝试过。

On CentOS, I fix this by

yum install readline-devel

and then recompile python 3.4.

On OpenSUSE, I fix this by

pip3 install readline

Referring to this answer:https://stackoverflow.com/a/26356378/2817654. Perhaps “pip3 install readline” is a general solution. Haven’t tried on my CentOS.


回答 9

在我的Mac OS python3中,您可以使用:control + p early命令contrlo + n next命令

In my mac os python3 you can use: control+p early command contrlo+n next command


回答 10

我发现我在下面复制的信息回答了这个问题

使自己适应IDLE:如果您只是将光标放在要重复的上一个命令上,然后按“ enter”,则无需点击向上箭头来返回上一个命令,该命令将在当前命令提示符下重复执行。再次按Enter键,命令将被执行。

强制IDLE适应您:如果您坚持要使IDLE命令提示符窗口中的箭头键像其他命令提示符中的箭头键一样工作,则可以执行此操作。转到“选项”菜单,选择“配置IDLE”,然后选择“密钥”。将与“上一个命令”和“下一个命令”关联的键分别更改为向上箭头和向下箭头。

资源

I find information that I copied below answer the question

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press “enter”, that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the “Options” menu, select “Configure IDLE”, and then “Keys”. Changing the key that is associated with the “previous command” and “next command” actions to be the up arrow, and down arrow, respectively.

source


回答 11

alt+p  
go into options tab
configure idle
Keys

在下面history-previous查找该命令,您可以在此处将其更改为更喜欢的命令。

alt+p  
go into options tab
configure idle
Keys

look under history-previous for the command, you can change it to something you like better once here.


回答 12

我不明白为什么会有这么长的解释。您所要做的就是安装pyreadline软件包,其中包括:

pip install py-readline

sudo端口安装py-readline(在Mac上)

(假设您已经安装了PIP。)

I don’t understand why there are so many long explanations about this. All you have to do is install the pyreadline package with:

pip install py-readline

sudo port install py-readline (on Mac)

(Assuming you have already installed PIP.)


回答 13

对于OSX,您不需要像pyfunc的答案这样的自定义脚本(至少在特立独行的情况下)。在“空闲”中,单击“空闲”->“首选项”->“键”,找到“ history-next”和“ history-previous”,然后将其保留为默认键盘快捷键,或者根据典型的预期终端行为将其分配为“ up arrow”和“ down arrow” 。

这是在OSX Mavericks的闲置2.7上。

You don’t need a custom script like pyfunc’s answer for OSX (at least on mavericks). In Idle click on Idle -> Preferences -> Keys, locate “history-next” and “history-previous”, and either leave them with their default keyboard shortcut or assign “up arrow” and “down arrow” per typical expected terminal behavior.

This is on Idle 2.7 on OSX Mavericks.


回答 14

如果您使用Debian Jessie,请运行此命令来修复系统安装 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

要修复我3.5.2pyenv安装的其他安装:

pip install readline

资料来源:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://stackoverflow.com/a/40229934/332788

If you use Debian Jessie run this to fix your system installation 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

To fix my other 3.5.2 installation which I installed with pyenv :

pip install readline

Sources:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://stackoverflow.com/a/40229934/332788


回答 15

使用箭头键转到命令的开头,然后按Enter键会将其复制为当前命令。

然后只需按Enter键即可再次运行它。

Using arrow keys to go to the start of the command and hitting enter copies it as the current command.

Then just hit enter to run it again.


回答 16

Ipython并非总是如此…我非常喜欢它,但是如果您尝试使用ipython运行Django shell。像>>>

ipython manage.py shell

如果使用virtualenv,它将无法正常工作。Django需要一些特殊的包含,如果您启动ipython则没有,因为它会启动默认的系统python,但不是虚拟的。

Ipython isn’t allways the way… I like it pretty much, but if you try run Django shell with ipython. Something like>>>

ipython manage.py shell

it does’n work correctly if you use virtualenv. Django needs some special includes which aren’t there if you start ipython, because it starts default system python, but not that virtual.


回答 17

当您运行python script.pyvs只是python进入交互式shell时,可能会发生这种情况,其中包括禁用readline的其他原因。

尝试:

import readline

This can happen when you run python script.py vs just python to enter the interactive shell, among other reasons for readline being disabled.

Try:

import readline

回答 18

向上箭头键仅在Python命令行中有效。

在IDLE(Python GUI)中,默认值为:Alt-p:检索与您键入的内容匹配的先前命令。Alt-n:下一次检索…例如,在Python 2.7.9中,您可以查看/更改操作键,选择:选项->配置IDLE->(制表符)键

Up Arrow works only in Python command line.

In IDLE (Python GUI) the defaults are: Alt-p : retrieves previous command matching what you have typed. Alt-n : retrieves next… In Python 2.7.9 for example, you can see/change the Action Keys selecting: Options -> Configure IDLE -> (Tab) Keys


回答 19

对于适用于python 3.5的anaconda,我需要安装 ncurses

conda install ncurses

ncurses安装标签完整,历史,并通过左右箭头导航在交互式shell工作。

For anaconda for python 3.5, I needed to install ncurses

conda install ncurses

After the ncurses install tab complete, history, and navigating via left and right arrows worked in the interactive shell.


回答 20

在使用Python 2.x的Mac上

➜ ~ brew install rlwrap

从rlwrap开始

➜ ~ rlwrap python

On Mac with Python 2.x

➜ ~ brew install rlwrap

Start with rlwrap

➜ ~ rlwrap python


回答 21

要在python中重复最后一个命令,可以<Alt + n>在Windows中使用

For repeating the last command in python, you can use <Alt + n> in windows


回答 22

向上箭头也对我有用。而且我不认为您需要为python内置命令行安装Readline模块。你应该尝试Ipython检查。也许这是键盘映射的问题。

Up arrow works for me too. And i don’t think you need to install the Readline module for python builtin commandline. U should try Ipython to check. Or maybe it’s the problem of your keybord map.


回答 23

如果使用MacOSX,请按control p向上或control n向下循环。我正在使用IDLE Python 3.4.1 Shell。

If using MacOSX, press control p to cycle up and control n to cycle down. I am using IDLE Python 3.4.1 Shell.


回答 24

在python 3.4 IDEL的Mac OS中是control + p

it is control + p in Mac os in python 3.4 IDEL


回答 25

在Ubuntu 16.04上,将Python从预加载的3.5 从源代码升级到3.7版后,我遇到了同样的问题。正如@erewok建议的那样,我做到了

sudo apt-get install libncurses-dev libreadline-dev

然后: sudo make install 在此之后,向上箭头键起作用了。不知道需要哪个模块来解决此问题,或者不能同时解决这两个问题,但是如果没有“ make install”,则任何模块都无法工作。在最初的制作过程中,出现了一些危险信号错误,但忽略并完成了构建。这次似乎没有任何错误。

On Ubuntu 16.04, I had the same problem after upgrading Python from the preloaded 3.5 to version 3.7 from source code. As @erewok suggested, I did

sudo apt-get install libncurses-dev libreadline-dev

followed by: sudo make install After that, the arrow-up key worked. Not sure which module is required to fix the problem or both, but without “make install”, none would work. During initial make, there were some red-flag errors, but ignored and completed the build. This time, there didn’t seem to have any errors.


如何将制表符完成添加到Python Shell?

问题:如何将制表符完成添加到Python Shell?

使用启动django应用程序时python manage.py shell,我得到一个InteractiveConsole shell-我可以使用制表符补全等。

Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

当仅使用启动python解释器时python,它不提供制表符补全功能。

有人可以告诉我django在做什么,以便给我一个交互式控制台,或者我需要做些什么来启动没有django应用程序的交互式控制台?

When starting a django application using python manage.py shell, I get an InteractiveConsole shell – I can use tab completion, etc.

Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)

When just starting a python interpreter using python, it doesn’t offer tab completion.

Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?


回答 0

我可能已经找到了一种方法。

创建一个文件.pythonrc

# ~/.pythonrc
# enable syntax completion
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

然后在您的.bashrc文件中,添加

export PYTHONSTARTUP=~/.pythonrc

这似乎有效。

I may have found a way to do it.

Create a file .pythonrc

# ~/.pythonrc
# enable syntax completion
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

then in your .bashrc file, add

export PYTHONSTARTUP=~/.pythonrc

That seems to work.


回答 1

我认为django的功能类似于https://docs.python.org/library/rlcompleter.html

如果您想拥有一个非常好的交互式解释器,请查看 IPython

I think django does something like https://docs.python.org/library/rlcompleter.html

If you want to have a really good interactive interpreter have a look at IPython.


回答 2

为了便于记录,本教程将对此进行介绍:http : //docs.python.org/tutorial/interactive.html

For the record, this is covered in the tutorial: http://docs.python.org/tutorial/interactive.html


回答 3

我使用ptpython。 https://github.com/jonathanslenders/ptpython/

ptpython是一个很棒的工具自动完成外壳cmd。安装ptpython非常简单,使用pip工具

pip安装ptpython

对于django shell,应该像这样导入django env

导入操作系统

os.environ.setdefault(“ DJANGO_SETTINGS_MODULE”,“ testweb.settings”)

相信我,这是最好的方式!!!

I use ptpython. https://github.com/jonathanslenders/ptpython/

ptpython is a wonderful tool autocomplete shell cmd. install ptpython is very easy,use pip tool

pip install ptpython

and for django shell,you should import the django env,like this

import os

os.environ.setdefault(“DJANGO_SETTINGS_MODULE”, “testweb.settings”)

Trust me,this is the best way to you!!!


回答 4

修复Windows10 Shell:

  • 点安装pyreadline
  • 点安装ipython [shell]

fix for windows10 shell:

  • pip install pyreadline
  • pip install ipython[shell]

回答 5

看起来python3开箱即用!

It looks like python3 has it out-of box!


回答 6

在Python3中,默认情况下启用此功能。我的系统未readline安装模块。我在Manjaro。我没有在其他Linux发行版(基本版,Ubuntu版,mint版)上遇到此制表符完成问题。

pip安装模块,而输入,它被扔以下错误-

ImportError: libncursesw.so.5: cannot open shared object file: No such file or directory

为了解决这个问题,我跑了

cd /usr/lib ln -s libncursesw.so libncursesw.so.5

这样解决了导入错误。并且,它也使python repl中的制表符完成,而没有对.pythonrcand的任何创建/更改.bashrc

In Python3 this feature is enabled by default. My system didn’t have the module readline installed. I am on Manjaro. I didn’t face this tab completion issue on other linux distributions (elementary, ubuntu, mint).

After pip installing the module, while importing, it was throwing the following error-

ImportError: libncursesw.so.5: cannot open shared object file: No such file or directory

To solve this, I ran-

cd /usr/lib ln -s libncursesw.so libncursesw.so.5

This resolved the import error. And, it also brought the tab completion in the python repl without any creation/changes of .pythonrc and .bashrc.


回答 7

是。它内置于3.6。

fernanr @ gnuruwi〜$ python3.6 Python 3.6.3(默认,Apr 10 2019,14:37:36)[Linux上的GCC 4.8.5 20150623(Red Hat 4.8.5-16)]键入“ help”,“ copyright ”,“信用”或“许可证”以获取更多信息。

导入操作系统。显示所有318种可能性?(y或n)os.CLD_CONTINUED os.O_RDONLY os.ST_NOEXEC os.environ os.getpid(os.readlink(os.spawnvpe(os.CLD_DUMPED os.O_RDWR os.ST_NOSUID os.environb os.getppid(os.getppid( .st

Yes. It’s built in to 3.6.

fernanr@gnuruwi ~ $ python3.6 Python 3.6.3 (default, Apr 10 2019, 14:37:36) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux Type “help”, “copyright”, “credits” or “license” for more information.

import os os. Display all 318 possibilities? (y or n) os.CLD_CONTINUED os.O_RDONLY os.ST_NOEXEC os.environ os.getpid( os.readlink( os.spawnvpe( os.CLD_DUMPED os.O_RDWR os.ST_NOSUID os.environb os.getppid( os.readv( os.st


回答 8

对于旧版本(2.x),上述脚本的工作方式类似于charm :)

fernanr@crsatx4 ~ $ cat .bashrc | grep -i python
#Tab completion for python shell
export PYTHONSTARTUP=~/.pythonrc
fernanr@crsatx4 ~ $ . ~/.bashrc
fernanr@crsatx4 ~ $ echo $?
0
fernanr@crsatx4 ~ $ python2
Python 2.7.5 (default, Jun 11 2019, 14:33:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.
Display all 249 possibilities? (y or n)
os.EX_CANTCREAT             os.O_WRONLY                 

For older versions (2.x) above script works like charm :)

fernanr@crsatx4 ~ $ cat .bashrc | grep -i python
#Tab completion for python shell
export PYTHONSTARTUP=~/.pythonrc
fernanr@crsatx4 ~ $ . ~/.bashrc
fernanr@crsatx4 ~ $ echo $?
0
fernanr@crsatx4 ~ $ python2
Python 2.7.5 (default, Jun 11 2019, 14:33:56)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.
Display all 249 possibilities? (y or n)
os.EX_CANTCREAT             os.O_WRONLY                 

Python 3在线解释器/ Shell

问题:Python 3在线解释器/ Shell

是否有使用Python 3 的在线解释器,例如http://codepad.org/http://www.trypython.org/

回答

由于问题已经结束,因此我在这里给出另一个答案。

Wandbox提供了多种语言的在线REPL,包括Python 2.x和3.x,C ++和Java。

Is there an online interpreter like http://codepad.org/ or http://www.trypython.org/ which uses Python 3?

Answer

Since the question is closed, I give another answer here.

Wandbox offers online REPLs for many languages, including Python 2.x and 3.x, C++ and Java.


回答 0

Ideone支持Python 2.6和Python 3

Ideone supports Python 2.6 and Python 3


回答 1

我最近在CompileOnline遇到了Python 3解释器。

I recently came across Python 3 interpreter at CompileOnline.


Python是否会优化掉仅用作返回值的变量?

问题:Python是否会优化掉仅用作返回值的变量?

以下两个代码段之间是否有最终区别?首先为函数中的变量分配一个值,然后返回该变量。第二个函数只是直接返回值。

Python是否将它们转换为等效的字节码?是其中之一吗?

情况1

def func():
    a = 42
    return a

情况2

def func():
    return 42

Is there any ultimate difference between the following two code snippets? The first assigns a value to a variable in a function and then returns that variable. The second function just returns the value directly.

Does Python turn them into equivalent bytecode? Is one of them faster?

Case 1:

def func():
    a = 42
    return a

Case 2:

def func():
    return 42

回答 0

不,不是

CPython字节码的编译仅通过小型的猫眼优化器传递,该优化器仅用于基本优化(有关这些优化的更多信息,请参见测试套件中的test_peepholer.py)。

要查看实际发生的情况,请使用dis*查看生成的指令。对于第一个函数,包含分配:

from dis import dis
dis(func)
  2           0 LOAD_CONST               1 (42)
              2 STORE_FAST               0 (a)

  3           4 LOAD_FAST                0 (a)
              6 RETURN_VALUE

而对于第二个功能:

dis(func2)
  2           0 LOAD_CONST               1 (42)
              2 RETURN_VALUE

第一个中使用了另外两个(快速)指令:STORE_FASTLOAD_FAST。这些可以快速存储并获取fastlocals当前执行帧数组中的值。然后,在两种情况下RETURN_VALUE都执行a。所以,第二个是曾经如此轻微,由于执行需要更少的命令更快。

通常,请注意CPython编译器在执行的优化中是保守的。它并没有像其他编译器一样聪明(通常也有更多的信息可以使用)。除了显然是正确的以外,主要设计目标是:a)保持简单,并且b)尽可能快地进行编译,因此您甚至不会注意到存在编译阶段。

最后,您不应该为像这样的小问题而烦恼。速度的好处是微小的,恒定的,并且与解释Python事实所带来的开销相形见war。

* dis是一个小的Python模块,可反汇编您的代码,您可以使用它查看VM将执行的Python字节码。

注意:正如@Jorn Vernee的评论中所述,这特定于Python的CPython实现。如果其他实现愿意的话,其他实现可能会进行更积极的优化,而CPython则不需要。

No, it doesn’t.

The compilation to CPython byte code is only passed through a small peephole optimizer that is designed to do only basic optimizations (See test_peepholer.py in the test suite for more on these optimizations).

To take a look at what’s actually going to happen, use dis* to see the instructions generated. For the first function, containing the assignment:

from dis import dis
dis(func)
  2           0 LOAD_CONST               1 (42)
              2 STORE_FAST               0 (a)

  3           4 LOAD_FAST                0 (a)
              6 RETURN_VALUE

While, for the second function:

dis(func2)
  2           0 LOAD_CONST               1 (42)
              2 RETURN_VALUE

Two more (fast) instructions are used in the first: STORE_FAST and LOAD_FAST. These make a quick store and grab of the value in the fastlocals array of the current execution frame. Then, in both cases, a RETURN_VALUE is performed. So, the second is ever so slightly faster due to less commands needed to execute.

In general, be aware that the CPython compiler is conservative in the optimizations it performs. It isn’t and doesn’t try to be as smart as other compilers (which, in general, also have much more information to work with). The main design goal, apart from obviously being correct, is to a) keep it simple and b) be as swift as possible in compiling these so you don’t even notice that a compilation phase exists.

In the end, you shouldn’t trouble yourself with small issues like this one. The benefit in speed is tiny, constant and, dwarfed by the overhead introduced by the fact that Python is interpreted.

*dis is a little Python module that dis-assembles your code, you can use it to see the Python bytecode that the VM will execute.

Note: As also stated in a comment by @Jorn Vernee, this is specific to the CPython implementation of Python. Other implementations might do more aggressive optimizations if they so desire, CPython doesn’t.


回答 1

两者基本上是相同的,除了在第一种情况下,对象42只是简单地分配给名为的变量a,换句话说,名称(即a)是指值(即42)。从某种意义上说,它从不复制任何数据,从技术上讲它不会做任何分配。

returning期间,此命名绑定a在第一种情况下返回,而对象42在第二种情况下返回。

有关更多阅读,请参考Ned Batchelder的精彩文章

Both are basically the same except that in the first case the object 42 is simply aassigned to a variable named a or, in other words, names (i.e. a) refer to values (i.e. 42) . It doesn’t do any assignment technically, in the sense that it never copies any data.

While returning, this named binding a is returned in the first case while the object 42 is return in the second case.

For more reading, refer this great article by Ned Batchelder


编译语言与口译语言

问题:编译语言与口译语言

我正在尝试更好地理解它们之间的区别。我在网上找到了很多解释,但是它们倾向于抽象的差异,而不是实际的含义。

我的大部分编程经验都来自CPython(动态的,解释的)和Java(静态的,编译的)。但是,我知道还有其他种类的解释和编译语言。除了可以从以编译语言编写的程序中分发可执行文件这一事实之外,每种类型是否都有优点/缺点?通常,我听到人们争辩说解释语言可以交互使用,但是我相信编译语言也可以具有交互实现,对吗?

I’m trying to get a better understanding of the difference. I’ve found a lot of explanations online, but they tend towards the abstract differences rather than the practical implications.

Most of my programming experiences has been with CPython (dynamic, interpreted), and Java (static, compiled). However, I understand that there are other kinds of interpreted and compiled languages. Aside from the fact that executable files can be distributed from programs written in compiled languages, are there any advantages/disadvantages to each type? Oftentimes, I hear people arguing that interpreted languages can be used interactively, but I believe that compiled languages can have interactive implementations as well, correct?


回答 0

编译语言是一种程序,一旦编译,该程序就会在目标计算机的指令中表示出来。例如,源代码中的加号“ +”操作可以直接转换为机器代码中的“ ADD”指令。

一种解释语言是其中所述指令不被目标机器直接执行,而是读取和执行通过一些其它方案(其通常写入本机机器的语言)。例如,解释器将在运行时识别相同的“ +”操作,然后使用适当的参数调用其自己的“ add(a,b)”函数,然后执行机器代码“ ADD”指令。

您可以使用解释语言或编译语言来做任何事情,反之亦然-它们都是图灵完整的。但是,两者在实现和使用上都有优点和缺点。

我将完全概括(纯粹主义者请原谅!),但是,粗略地讲,这是编译语言的优点:

  • 通过直接使用目标计算机的本机代码来提高性能
  • 在编译阶段进行功能强大的优化的机会

以下是解释语言的优点:

  • 易于实现(编写好的编译器非常困难!)
  • 无需运行编译阶段:可以“即时”直接执行代码
  • 可以更方便地使用动态语言

请注意,诸如字节码编译之类的现代技术增加了一些额外的复杂性-此处发生的是,编译器针对的是“虚拟机”,该“虚拟机”与底层硬件不同。然后可以在以后的阶段再次编译这些虚拟机指令,以获取本机代码(例如,由Java JVM JIT编译器完成)。

A compiled language is one where the program, once compiled, is expressed in the instructions of the target machine. For example, an addition “+” operation in your source code could be translated directly to the “ADD” instruction in machine code.

An interpreted language is one where the instructions are not directly executed by the target machine, but instead read and executed by some other program (which normally is written in the language of the native machine). For example, the same “+” operation would be recognised by the interpreter at run time, which would then call its own “add(a,b)” function with the appropriate arguments, which would then execute the machine code “ADD” instruction.

You can do anything that you can do in an interpreted language in a compiled language and vice-versa – they are both Turing complete. Both however have advantages and disadvantages for implementation and use.

I’m going to completely generalise (purists forgive me!) but, roughly, here are the advantages of compiled languages:

  • Faster performance by directly using the native code of the target machine
  • Opportunity to apply quite powerful optimisations during the compile stage

And here are the advantages of interpreted languages:

  • Easier to implement (writing good compilers is very hard!!)
  • No need to run a compilation stage: can execute code directly “on the fly”
  • Can be more convenient for dynamic languages

Note that modern techniques such as bytecode compilation add some extra complexity – what happens here is that the compiler targets a “virtual machine” which is not the same as the underlying hardware. These virtual machine instructions can then be compiled again at a later stage to get native code (e.g. as done by the Java JVM JIT compiler).


回答 1

语言本身既不会编译也不会解释,而仅是语言的特定实现。Java是一个完美的例子。有一个基于字节码的平台(JVM),一个本机编译器(gcj)和一个Java超集的插入器(bsh)。那么,Java现在是什么?字节码编译,本机编译还是解释?

Scala,Haskell或Ocaml是经过编译和解释的其他语言。这些语言中的每一种都有一个交互式解释器,以及用于字节码或本机代码的编译器。

因此,通常通过“编译”和“解释”对语言进行分类没有多大意义。

A language itself is neither compiled nor interpreted, only a specific implementation of a language is. Java is a perfect example. There is a bytecode-based platform (the JVM), a native compiler (gcj) and an interpeter for a superset of Java (bsh). So what is Java now? Bytecode-compiled, native-compiled or interpreted?

Other languages, which are compiled as well as interpreted, are Scala, Haskell or Ocaml. Each of these languages has an interactive interpreter, as well as a compiler to byte-code or native machine code.

So generally categorizing languages by “compiled” and “interpreted” doesn’t make much sense.


回答 2

开始思考:过去的爆炸

很久很久以前,曾经有计算解释器和编译器。各种大惊小怪的结果使一个人的优胜劣汰。普遍的观点在当时是沿着线的东西:

  • 口译员:快速开发(编辑和运行)。执行速度很慢,因为每个语句每次执行时都必须将其解释为机器代码(想想这对于执行数千次循环意味着什么)。
  • 编译器:开发缓慢(编辑,编译,链接和运行。编译/链接步骤可能需要花费大量时间)。快速执行。整个程序已经在本机代码中。

在解释的程序和编译的程序之间存在一个或两个数量级的运行时性能差异。其他区别点,例如代码的运行时可变性,也引起了一些关注,但主要区别在于运行时性能问题。

如今,景观已发展到某种程度,以至于汇编/解释的区别几乎是无关紧要的。许多编译语言要求运行时服务不是完全基于机器代码的。而且,大多数解释语言在执行之前都会被“编译”为字节码。字节码解释器可能非常高效,并且从执行速度的角度来看,可以与某些编译器生成的代码相媲美。

经典的区别是,编译器使用某种运行时系统生成本机代码,解释器读取源代码并动态生成代码。如今,几乎没有经典的解释器了-几乎所有经典的解释器都编译成字节码(或其他半编译状态),然后在虚拟“机器”上运行。

Start thinking in terms of a: blast from the past

Once upon a time, long long ago, there lived in the land of computing interpreters and compilers. All kinds of fuss ensued over the merits of one over the other. The general opinion at that time was something along the lines of:

  • Interpreter: Fast to develop (edit and run). Slow to execute because each statement had to be interpreted into machine code every time it was executed (think of what this meant for a loop executed thousands of times).
  • Compiler: Slow to develop (edit, compile, link and run. The compile/link steps could take serious time). Fast to execute. The whole program was already in native machine code.

A one or two order of magnitude difference in the runtime performance existed between an interpreted program and a compiled program. Other distinguishing points, run-time mutability of the code for example, were also of some interest but the major distinction revolved around the run-time performance issues.

Today the landscape has evolved to such an extent that the compiled/interpreted distinction is pretty much irrelevant. Many compiled languages call upon run-time services that are not completely machine code based. Also, most interpreted languages are “compiled” into byte-code before execution. Byte-code interpreters can be very efficient and rival some compiler generated code from an execution speed point of view.

The classic difference is that compilers generated native machine code, interpreters read source code and generated machine code on the fly using some sort of run-time system. Today there are very few classic interpreters left – almost all of them compile into byte-code (or some other semi-compiled state) which then runs on a virtual “machine”.


回答 3

极端简单的情况:

  • 编译器将生成目标计算机的本机可执行文件格式的二进制可执行文件。该二进制文件包含除系统库以外的所有必需资源。它无需任何准备和处理即可运行,并且像闪电一样运行,因为该代码是目标计算机上CPU的本机代码。

  • 解释器将在循环中向用户显示提示,用户可以在其中输入语句或代码,并且在命中RUN或等效命令时,解释器将检查,扫描,解析并以解释方式执行每一行,直到程序运行至停止点或错误为止。因为每一行都是独立处理的,并且解释器不会从以前的行中“学到”任何东西,所以每行每次都需要将人类可读的语言转换为机器指令,所以这太慢了。从好的方面来说,用户可以通过各种方式检查程序并与之交互:更改变量,更改代码,在跟踪或调试模式下运行……等等。

顺便说一句,让我解释一下生活不再那么简单了。例如,

  • 许多解释器会预编译给出的代码,因此不必一次又一次地重复翻译步骤。
  • 一些编译器不编译为特定于CPU的机器指令,而是编译为字节码,这是一种虚拟机器的人造机器代码。这使编译后的程序更具可移植性,但是在每个目标系统上都需要一个字节码解释器。
  • 字节码解释器(我现在在这里看着Java)倾向于在执行之前为目标部分的CPU重新编译它们获得的字节码(称为JIT)。为了节省时间,通常只对经常运行的代码(热点)执行此操作。
  • 一些看起来和行为像解释器的系统(例如,Clojure)会立即编译它们获得的任何代码,但允许以交互方式访问程序环境。从根本上来说,这就是二进制编译器为解释器带来的便利。
  • 一些编译器并没有真正编译,只是预消化和压缩代码。我听说前阵子就是Perl的工作方式。因此,有时编译器只是在做一些工作,而且大部分仍在解释中。

最终,如今,解释与编译是一个折衷方案,花费(一次)编译的时间通常会因更好的运行时性能而获得回报,但是解释性环境为交互提供了更多机会。编译与解释主要是关于如何“理解”程序的工作如何在不同的过程之间进行划分的问题,而如今,由于语言和产品试图同时兼顾两者的优势,这条线有些模糊。

The extreme and simple cases:

  • A compiler will produce a binary executable in the target machine’s native executable format. This binary file contains all required resources except for system libraries; it’s ready to run with no further preparation and processing and it runs like lightning because the code is the native code for the CPU on the target machine.

  • An interpreter will present the user with a prompt in a loop where he can enter statements or code, and upon hitting RUN or the equivalent the interpreter will examine, scan, parse and interpretatively execute each line until the program runs to a stopping point or an error. Because each line is treated on its own and the interpreter doesn’t “learn” anything from having seen the line before, the effort of converting human-readable language to machine instructions is incurred every time for every line, so it’s dog slow. On the bright side, the user can inspect and otherwise interact with his program in all kinds of ways: Changing variables, changing code, running in trace or debug modes… whatever.

With those out of the way, let me explain that life ain’t so simple any more. For instance,

  • Many interpreters will pre-compile the code they’re given so the translation step doesn’t have to be repeated again and again.
  • Some compilers compile not to CPU-specific machine instructions but to bytecode, a kind of artificial machine code for a ficticious machine. This makes the compiled program a bit more portable, but requires a bytecode interpreter on every target system.
  • The bytecode interpreters (I’m looking at Java here) recently tend to re-compile the bytecode they get for the CPU of the target section just before execution (called JIT). To save time, this is often only done for code that runs often (hotspots).
  • Some systems that look and act like interpreters (Clojure, for instance) compile any code they get, immediately, but allow interactive access to the program’s environment. That’s basically the convenience of interpreters with the speed of binary compilation.
  • Some compilers don’t really compile, they just pre-digest and compress code. I heard a while back that’s how Perl works. So sometimes the compiler is just doing a bit of the work and most of it is still interpretation.

In the end, these days, interpreting vs. compiling is a trade-off, with time spent (once) compiling often being rewarded by better runtime performance, but an interpretative environment giving more opportunities for interaction. Compiling vs. interpreting is mostly a matter of how the work of “understanding” the program is divided up between different processes, and the line is a bit blurry these days as languages and products try to offer the best of both worlds.


回答 4

来自http://www.quora.com/What-is-the-difference-between-compiled-and-interpreted-programming-languages

这没有什么区别,因为“编译程序设计语言”和“解释程序设计语言”不是有意义的概念。任何编程语言(实际上是任何一种编程语言)都可以解释或编译。因此,解释和编译是实现技术,而不是语言的属性。

解释是一种技术,通过该技术,另一个程序(解释器)代表正在解释的程序执行操作以使其运行。如果您可以想象阅读程序并按照程序说的做一步一步,例如在草稿纸上说,那也是解释器的工作。解释程序的常见原因是解释器相对容易编写。另一个原因是,解释器可以监视程序在运行时试图执行的操作,以执行安全性策略。

编译是一种技术,通过该技术可以将用一种语言(“源语言”)编写的程序转换为另一种语言(“目标语言”)的程序,这希望与原始程序具有相同的含义。在进行翻译时,编译器通常还会尝试以使目标程序更快的方式(不改变其含义!)对程序进行转换。编译程序的一个常见原因是,有一种很好的方法可以以目标语言快速运行程序,而无需一路解释源语言。

根据上述定义,您可能已经猜到这两种实现技术不是互斥的,甚至可能是互补的。传统上,编译器的目标语言是机器代码或类似的东西,它表示特定计算机CPU可以理解的任何数量的编程语言。然后,机器代码将“运行在金属上”(尽管如果看起来足够接近,人们可能会发现“金属”的工作原理很像解释器)。但是,如今,使用编译器生成要解释的目标代码已经非常普遍了,例如,Java曾经(有时仍然这样做)就是这种方式。有些编译器会将其他语言翻译成JavaScript,然后通常在网络浏览器中运行,这些浏览器可能会解释JavaScript,或将其编译为虚拟机或本机代码。我们还提供了机器码解释器,可用于在另一种机器上模拟一种硬件。或者,可以使用编译器生成目标代码,然后该目标代码将成为另一编译器的源代码,后者甚至可以及时在内存中编译代码以使其运行,然后依次运行。。。你明白了。有很多方法可以组合这些概念。

From http://www.quora.com/What-is-the-difference-between-compiled-and-interpreted-programming-languages

There is no difference, because “compiled programming language” and “interpreted programming language” aren’t meaningful concepts. Any programming language, and I really mean any, can be interpreted or compiled. Thus, interpretation and compilation are implementation techniques, not attributes of languages.

Interpretation is a technique whereby another program, the interpreter, performs operations on behalf of the program being interpreted in order to run it. If you can imagine reading a program and doing what it says to do step-by-step, say on a piece of scratch paper, that’s just what an interpreter does as well. A common reason to interpret a program is that interpreters are relatively easy to write. Another reason is that an interpreter can monitor what a program tries to do as it runs, to enforce a policy, say, for security.

Compilation is a technique whereby a program written in one language (the “source language”) is translated into a program in another language (the “object language”), which hopefully means the same thing as the original program. While doing the translation, it is common for the compiler to also try to transform the program in ways that will make the object program faster (without changing its meaning!). A common reason to compile a program is that there’s some good way to run programs in the object language quickly and without the overhead of interpreting the source language along the way.

You may have guessed, based on the above definitions, that these two implementation techniques are not mutually exclusive, and may even be complementary. Traditionally, the object language of a compiler was machine code or something similar, which refers to any number of programming languages understood by particular computer CPUs. The machine code would then run “on the metal” (though one might see, if one looks closely enough, that the “metal” works a lot like an interpreter). Today, however, it’s very common to use a compiler to generate object code that is meant to be interpreted—for example, this is how Java used to (and sometimes still does) work. There are compilers that translate other languages to JavaScript, which is then often run in a web browser, which might interpret the JavaScript, or compile it a virtual machine or native code. We also have interpreters for machine code, which can be used to emulate one kind of hardware on another. Or, one might use a compiler to generate object code that is then the source code for another compiler, which might even compile code in memory just in time for it to run, which in turn . . . you get the idea. There are many ways to combine these concepts.


回答 5

与已编译的源代码相比,已解释的源代码的最大优势是PORTABILITY

如果您的源代码已编译,则需要为要在其上运行程序的每种类型的处理器和/或平台编译一个不同的可执行文件(例如,一个用于Windows x86,一个用于Windows x64,一个用于Linux x64,等等。上)。此外,除非您的代码完全符合标准并且不使用任何平台特定的功能/库,否则您实际上将需要编写和维护多个代码库!

如果您的源代码被解释,则只需编写一次即可,并且可以由任何平台上的适当解释器来解释和执行它!它是便携式的!需要注意的是一个解释器本身是一个可执行程序编写和编译为特定平台。

编译后代码的一个优点是,它向最终用户隐藏了源代码(可能是知识产权),因为您部署了晦涩的二进制可执行文件,而不是部署原始的人类可读源代码。

The biggest advantage of interpreted source code over compiled source code is PORTABILITY.

If your source code is compiled, you need to compile a different executable for each type of processor and/or platform that you want your program to run on (e.g. one for Windows x86, one for Windows x64, one for Linux x64, and so on). Furthermore, unless your code is completely standards compliant and does not use any platform-specific functions/libraries, you will actually need to write and maintain multiple code bases!

If your source code is interpreted, you only need to write it once and it can be interpreted and executed by an appropriate interpreter on any platform! It’s portable! Note that an interpreter itself is an executable program that is written and compiled for a specific platform.

An advantage of compiled code is that it hides the source code from the end user (which might be intellectual property) because instead of deploying the original human-readable source code, you deploy an obscure binary executable file.


回答 6

编译器和解释器完成相同的工作:将编程语言翻译为另一种编程语言,通常更接近硬件,通常指导可执行的机器代码。

传统上,“编译”是指这种翻译一次完成,由开发人员完成,然后将生成的可执行文件分发给用户。纯粹的例子:C ++。编译通常花费很长时间,并尝试进行大量昂贵的优化,以使生成的可执行文件运行更快。最终用户没有工具和知识来自己编译东西,并且可执行文件通常必须在各种硬件上运行,因此您不能进行许多针对硬件的优化。在开发过程中,单独的编译步骤意味着更长的反馈周期。

传统上,“已解释”是指当用户要运行程序时,翻译是“即时”进行的。纯粹的例子:香草PHP。天真的解释器每次运行时都必须解析和翻译每段代码,这使其非常慢。它无法进行复杂,成本高昂的优化,因为它们所花费的时间比执行所节省的时间还要长。但是它可以充分利用其运行的硬件的功能。缺少单独的编译步骤可减少开发过程中的反馈时间。

但是如今,“编译与解释”已不是一个黑白问题,介于两者之间。天真的,简单的口译员已经绝迹了。许多语言使用两步过程,其中将高级代码转换为平台无关的字节码(解释起来更快)。然后,您将拥有“及时编译器”,每个程序运行一次最多编译一次代码,有时缓存结果,甚至可以明智地决定解释很少运行的代码,并对运行频繁的代码进行强大的优化。在开发过程中,调试器甚至可以针对传统编译语言在正在运行的程序中切换代码。

A compiler and an interpreter do the same job: translating a programming language to another pgoramming language, usually closer to the hardware, often direct executable machine code.

Traditionally, “compiled” means that this translation happens all in one go, is done by a developer, and the resulting executable is distributed to users. Pure example: C++. Compilation usually takes pretty long and tries to do lots of expensive optmization so that the resulting executable runs faster. End users don’t have the tools and knowledge to compile stuff themselves, and the executable often has to run on a variety of hardware, so you can’t do many hardware-specific optimizations. During development, the separate compilation step means a longer feedback cycle.

Traditionally, “interpreted” means that the translation happens “on the fly”, when the user wants to run the program. Pure example: vanilla PHP. A naive interpreter has to parse and translate every piece of code every time it runs, which makes it very slow. It can’t do complex, costly optimizations because they’d take longer than the time saved in execution. But it can fully use the capabilities of the hardware it runs on. The lack of a separrate compilation step reduces feedback time during development.

But nowadays “compiled vs. interpreted” is not a black-or-white issue, there are shades in between. Naive, simple interpreters are pretty much extinct. Many languages use a two-step process where the high-level code is translated to a platform-independant bytecode (which is much faster to interpret). Then you have “just in time compilers” which compile code at most once per program run, sometimes cache results, and even intelligently decide to interpret code that’s run rarely, and do powerful optimizations for code that runs a lot. During development, debuggers are capable of switching code inside a running program even for traditionally compiled languages.


回答 7

首先,澄清一下,Java不是完全以C ++的方式静态编译和链接的。它被编译成字节码,然后由JVM解释。JVM可以及时对本机语言进行编译,但不必这样做。

更重要的是:我认为互动是主要的实际差异。由于所有内容均已解释,因此您可以摘录一小段代码,然后针对环境的当前状态进行解析和运行。因此,如果您已经执行过初始化变量的代码,则可以访问该变量,等等。它确实可以将其自身用于诸如功能样式之类的事情。

但是,解释会花费很多,尤其是当您拥有一个具有大量引用和上下文的大型系统时。根据定义,这是浪费的,因为可能必须两次解释和优化相同的代码(尽管大多数运行时对此都有一些缓存和优化)。尽管如此,您仍然需要支付运行时成本,并且经常需要运行时环境。您也不太可能看到复杂的过程间优化,因为目前它们的性能还不够互动。

因此,对于那些变化不大的大型系统,对于某些语言而言,预编译和预链接所有内容更有意义,请执行您可以做的所有优化。最终将获得非常精益的运行时,该运行时已针对目标计算机进行了优化。

至于生成可执行文件,与恕我直言无关。您通常可以使用编译语言创建可执行文件。但是,您也可以使用解释语言创建可执行文件,只是解释器和运行时已打包在可执行文件中,并且对您隐藏了。这意味着您通常仍需支付运行时成本(尽管我确信对于某些语言,有一些方法可以将所有内容转换为树可执行文件)。

我不同意所有语言都可以互动。某些语言(例如C)与机器和整个链接结构紧密相关,因此我不确定您是否可以构建有意义的完整交互式版本

First, a clarification, Java is not fully static-compiled and linked in the way C++. It is compiled into bytecode, which is then interpreted by a JVM. The JVM can go and do just-in-time compilation to the native machine language, but doesn’t have to do it.

More to the point: I think interactivity is the main practical difference. Since everything is interpreted, you can take a small excerpt of code, parse and run it against the current state of the environment. Thus, if you had already executed code that initialized a variable, you would have access to that variable, etc. It really lends itself way to things like the functional style.

Interpretation, however, costs a lot, especially when you have a large system with a lot of references and context. By definition, it is wasteful because identical code may have to be interpreted and optimized twice (although most runtimes have some caching and optimizations for that). Still, you pay a runtime cost and often need a runtime environment. You are also less likely to see complex interprocedural optimizations because at present their performance is not sufficiently interactive.

Therefore, for large systems that are not going to change much, and for certain languages, it makes more sense to precompile and prelink everything, do all the optimizations that you can do. This ends up with a very lean runtime that is already optimized for the target machine.

As for generating executbles, that has little to do with it, IMHO. You can often create an executable from a compiled language. But you can also create an executable from an interpreted language, except that the interpreter and runtime is already packaged in the exectuable and hidden from you. This means that you generally still pay the runtime costs (although I am sure that for some language there are ways to translate everything to a tree executable).

I disagree that all languages could be made interactive. Certain languages, like C, are so tied to the machine and the entire link structure that I’m not sure you can build a meaningful fully-fledged interactive version


回答 8

给出实际答案相当困难,因为区别在于语言定义本身。可以为每种编译语言构建解释器,但不可能为每种解释语言构建编译器。语言的形式定义非常重要。从而使理论上的信息学方面的东西更受大学的欢迎。

It’s rather difficult to give a practical answer because the difference is about the language definition itself. It’s possible to build an interpreter for every compiled language, but it’s not possible to build an compiler for every interpreted language. It’s very much about the formal definition of a language. So that theoretical informatics stuff noboby likes at university.


回答 9

Python图书©2015 Imagine Publishing Ltd,仅通过第10页中提到的以下提示来区分差异:

一种解释性语言(例如Python)是一种将源代码转换为机器代码,然后在每次程序运行时执行的语言。这与诸如C之类的编译语言不同,后者仅将源代码转换为机器代码一次-每次程序运行时都会执行生成的机器代码。

The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.


回答 10

编译是从以编译的编程语言编写的代码创建可执行程序的过程。编译允许计算机运行和理解程序,而无需使用用于创建该程序的编程软件。编译程序时,通常是针对特定平台(例如IBM平台)编译的,该平台可与IBM兼容计算机一起使用,但不适用于其他平台(例如Apple平台)。第一个编译器是由Grace Hopper在哈佛Mark I计算机上开发的。今天,大多数高级语言将包括其自己的编译器或可用的工具包,可用于编译程序。与Java一起使用的编译器的一个很好的例子是Eclipse,而与C和C ++一起使用的编译器的一个例子是gcc命令。

Compile is the process of creating an executable program from code written in a compiled programming language. Compiling allows the computer to run and understand the program without the need of the programming software used to create it. When a program is compiled it is often compiled for a specific platform (e.g. IBM platform) that works with IBM compatible computers, but not other platforms (e.g. Apple platform). The first compiler was developed by Grace Hopper while working on the Harvard Mark I computer. Today, most high-level languages will include their own compiler or have toolkits available that can be used to compile the program. A good example of a compiler used with Java is Eclipse and an example of a compiler used with C and C++ is the gcc command. Depending on how big the program is it should take a few seconds or minutes to compile and if no errors are encountered while being compiled an executable file is created.check this information


回答 11

简短(不精确)的定义:

编译语言:整个程序立即转换为机器代码,然后由CPU运行机器代码。

解释的语言:逐行读取程序,一旦读取一行,CPU就会执行该行的机器指令。

但是,实际上,如今只有很少的语言是纯编译的或纯解释的,通常是混合的。有关图片的详细说明,请参见以下线程:

编译和解释之间有什么区别?

或我后来的博客文章:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/

Short (un-precise) definition:

Compiled language: Entire program is translated to machine code at once, then the machine code is run by the CPU.

Interpreted language: Program is read line-by-line and as soon as a line is read the machine instructions for that line are executed by the CPU.

But really, few languages these days are purely compiled or purely interpreted, it often is a mix. For a more detailed description with pictures, see this thread:

What is the difference between compilation and interpretation?

Or my later blog post:

https://orangejuiceliberationfront.com/the-difference-between-compiler-and-interpreter/