标签归档:python-idle

如何在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.


如何打开IDLE中的行号?

问题:如何打开IDLE中的行号?

在IDLE的主外壳中,错误总是返回行号,但是开发环境甚至没有行号。反正有打开行号吗?

In the main shell of IDLE, errors always return a line number but the development environment doesn’t even have line numbers. Is there anyway to turn on line numbers?


回答 0

3.8版或更高版本:

要在当前窗口中显示行号,请转到,Options然后单击Show Line Numbers

要自动显示他们,去Options> Configure IDLE> General并检查Show line numbers in new windows框。

3.7版或更高版本:

不幸的是,尽管为此有一个增强请求,但没有选择在IDLE中显示行号。

但是,有两种方法可以解决此问题:

  1. 在编辑菜单下,有一个转到行选项(为此存在默认的Alt + G快捷键)。

  2. 右下角有一个显示,告诉您当前的行号/行的位置:

Version 3.8 or newer:

To show line numbers in the current window, go to Options and click Show Line Numbers.

To show them automatically, go to Options > Configure IDLE > General and check the Show line numbers in new windows box.

Version 3.7 or older:

Unfortunately there is not an option to display line numbers in IDLE although there is an enhancement request open for this.

However, there are a couple of ways to work around this:

  1. Under the edit menu there is a go to line option (there is a default shortcut of Alt+G for this).

  2. There is a display at the bottom right which tells you your current line number / position on the line:


回答 1

IDLE有一组有用的扩展,称为IDLEX,可与MacOS和Windows一起使用http://idlex.sourceforge.net/

它包括行号,我觉得它非常方便和免费。

否则,还有许多其他IDE,其中一些是免费的:https : //wiki.python.org/moin/IntegratedDevelopmentEnvironments

There’s a set of useful extensions to IDLE called IDLEX that works with MacOS and Windows http://idlex.sourceforge.net/

It includes line numbering and I find it quite handy & free.

Otherwise there are a bunch of other IDEs some of which are free: https://wiki.python.org/moin/IntegratedDevelopmentEnvironments


回答 2

如果您要查找导致错误的行,请在显示该行错误的Python shell中单击鼠标右键,它将显示“转到文件/行”,直接将您带到相关行。

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a “Go to file/line” which takes you directly to the line in question.


回答 3

正如达沃斯所说,您可以使用IDLEX

碰巧我正在使用Linux版本,并且从所有扩展名开始,我只需要LineNumbers。因此,我下载了IDLEX存档,从其中获取LineNumbers.py,将其复制到Python的lib文件夹(在我的情况下为/usr/lib/python3.5/idlelib),并将以下几行添加到主文件夹中的配置文件中: 〜/ .idlerc / config-extensions.cfg:

[LineNumbers]
enable = 1
enable_shell = 0
visible = True

[LineNumbers_cfgBindings]
linenumbers-show = 

As it was mentioned by Davos you can use the IDLEX

It happens that I’m using Linux version and from all extensions I needed only LineNumbers. So I’ve downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python’s lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:

[LineNumbers]
enable = 1
enable_shell = 0
visible = True

[LineNumbers_cfgBindings]
linenumbers-show = 

回答 4

行号已在两天前添加到IDLE编辑器中,并将出现在即将发布的3.8.0a3和更高版本的3.7.5中。对于新窗口,默认情况下它们处于关闭状态,但是可以在“设置”对话框的“常规”选项卡的“编辑器”部分将其撤消。对于现有窗口,在“选项”菜单上有一个新的“显示(隐藏)行号”条目。当前没有热键。可以通过单击一条线或单击并拖动来选择一条线或一组线。

有些人可能错过了“编辑/转到行”。右键单击上下文菜单转到文件/行可用于grep(在文件中查找)输出以及引用。

Line numbers were added to the IDLE editor two days ago and will appear in the upcoming 3.8.0a3 and later 3.7.5. For new windows, they are off by default, but this can be reversed on the Setting dialog, General tab, Editor section. For existing windows, there is a new Show (Hide) Line Numbers entry on the Options menu. There is currently no hotkey. One can select a line or bloc of lines by clicking on a line or clicking and dragging.

Some people may have missed Edit / Go to Line. The right-click context menu Goto File/Line works on grep (Find in Files) output as well as on trackbacks.


回答 5

由于@StahlRat已回答。我想为其添加另一种方法。有用于Python默认空闲编辑器Python扩展包的扩展包

As @StahlRat already answered. I would like to add another method for it. There is extension pack for Python Default idle editor Python Extensions Package.


回答 6

如上所述(一种快速的方法):

pip install IDLEX

然后,我在桌面(Win10)上创建一个快捷方式,如下所示:

C:\Python\Python37\pythonw.exe "C:\Python\Python37\Scripts\idlex.pyw"

路径可能不同,需要更改:

C:\Python\Python37

(感谢上面的精彩回答)

As mentioned above (a quick way to do this) :

pip install IDLEX

Then I create a shortcut on Desktop (Win10) like this:

C:\Python\Python37\pythonw.exe "C:\Python\Python37\Scripts\idlex.pyw"

The paths may be different and need to be changed:

C:\Python\Python37

(Thanks for the great answers above)


如何从IDLE访问命令历史记录?

问题:如何从IDLE访问命令历史记录?

在bash或Window的命令提示符上,我们可以按键盘上的向上箭头以获取最后一个命令,然后对其进行编辑,然后再次按Enter以查看结果。

但是在Python的IDLE 2.6.5或3.1.2中,似乎如果我们的语句打印出了25行,我们需要按向上箭头25次到最后一个命令,然后按Enter才能将其复制?

还是使用鼠标查明该行并单击那里,然后按Enter键进行复制?有没有更快的方法?

On bash or Window’s Command Prompt, we can press the up arrow on keyboard to get the last command, and edit it, and press ENTER again to see the result.

But in Python’s IDLE 2.6.5 or 3.1.2, it seems if our statement prints out 25 lines, we need to press the up arrow 25 times to that last command, and press ENTER for it to be copied?

Or use the mouse to pinpoint that line and click there, and press ENTER to copy? Is there a faster way?


回答 0

  • 我认为您正在寻找history-previous action,默认情况下绑定到Alt+ P
  • 您可以在“ 选项->配置IDLE->密钥 ”中重新映射它
  • 您还可以从IDLE的顶部菜单访问此命令:“ Shell-> Previous History

顺便说一句,为什么不尝试像bpythonipython这样的更好的外壳(对于初学者来说更难看)?

  • I think you are looking for the history-previous action, which is bound to Alt+P by default.
  • You can remap it in “Options -> Configure IDLE -> Keys
  • You can also access this command from the top menu in IDLE: “Shell -> Previous History

Incidentally, why don’t you try a better (less ugly, for starters) shell like bpython or ipython?


回答 1

只是Alt+P用来上去。同样,Alt+N可以用来下降。

just use Alt+P to go up. Similarly, Alt+N could be used to go down.


回答 2

如果您使用的是Mac,则为ctrl+ p

If you’re on mac, it’s ctrl+p.


回答 3

进入“首选项”>“键”。在列表中找到“历史上一个”选项,并将其编辑为“向上箭头”。

Go into Preferences > Keys. Find the ‘history-previous’ selection in the list and edit it to Up Arrow.


回答 4

默认情况下,您始终可以编辑〜/ .idlerc下的config-keys.cfg文件。查找条目“ history-previous”,并将其设置为如下所示…

history-previous = <Key-Up>

做完了

You can always edit the file config-keys.cfg found under ~/.idlerc by default; look for the entry “history-previous” and set it to as below…

history-previous = <Key-Up>

Done.


如何从IDLE交互式shell运行python脚本?

问题:如何从IDLE交互式shell运行python脚本?

如何从IDLE交互式外壳程序中运行python脚本?

以下引发错误:

>>> python helloworld.py
SyntaxError: invalid syntax

How do I run a python script from within the IDLE interactive shell?

The following throws an error:

>>> python helloworld.py
SyntaxError: invalid syntax

回答 0

Python3

exec(open('helloworld.py').read())

如果您的文件不在同一目录中:

exec(open('./app/filename.py').read())

有关传递全局/局部变量的信息,请参阅https://stackoverflow.com/a/437857/739577


在不推荐使用的Python版本中

Python2 内置函数:execfile

execfile('helloworld.py')

通常不能用参数调用它。但是,有一个解决方法:

import sys
sys.argv = ['helloworld.py', 'arg']  # argv[0] should still be the script name
execfile('helloworld.py')

从2.6开始不推荐使用:popen

import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout

带参数:

os.popen('python helloworld.py arg').read()

预先使用:子流程

import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout

带参数:

subprocess.call(['python', 'helloworld.py', 'arg'])

阅读文档以获取详细信息:-)


用这个基础测试helloworld.py

import sys
if len(sys.argv) > 1:
    print(sys.argv[1])

Python3:

exec(open('helloworld.py').read())

If your file not in the same dir:

exec(open('./app/filename.py').read())

See https://stackoverflow.com/a/437857/739577 for passing global/local variables.


In deprecated Python versions

Python2 Built-in function: execfile

execfile('helloworld.py')

It normally cannot be called with arguments. But here’s a workaround:

import sys
sys.argv = ['helloworld.py', 'arg']  # argv[0] should still be the script name
execfile('helloworld.py')

Deprecated since 2.6: popen

import os
os.popen('python helloworld.py') # Just run the program
os.popen('python helloworld.py').read() # Also gets you the stdout

With arguments:

os.popen('python helloworld.py arg').read()

Advance usage: subprocess

import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout

With arguments:

subprocess.call(['python', 'helloworld.py', 'arg'])

Read the docs for details :-)


Tested with this basic helloworld.py:

import sys
if len(sys.argv) > 1:
    print(sys.argv[1])

回答 1

您可以在python3中使用它:

exec(open(filename).read())

You can use this in python3:

exec(open(filename).read())

回答 2

空闲外壳窗口与终端外壳(例如,运行shbash)不同。而是就像在Python交互式解释器(python -i)中一样。在IDLE中运行脚本的最简单方法是使用菜单中的Open命令File(这可能会有所不同,具体取决于运行的平台),将脚本文件加载到IDLE编辑器窗口中,然后使用Run-> Run Module命令(快捷方式F5)。

The IDLE shell window is not the same as a terminal shell (e.g. running sh or bash). Rather, it is just like being in the Python interactive interpreter (python -i). The easiest way to run a script in IDLE is to use the Open command from the File menu (this may vary a bit depending on which platform you are running) to load your script file into an IDLE editor window and then use the Run -> Run Module command (shortcut F5).


回答 3

试试这个

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])

Try this

import os
import subprocess

DIR = os.path.join('C:\\', 'Users', 'Sergey', 'Desktop', 'helloword.py')

subprocess.call(['python', DIR])

回答 4

execFile('helloworld.py')为我做这份工作。需要注意的是,如果.py文件不在Python文件夹本身中,请输入.py文件的完整目录名称(至少在Windows中是这种情况)

例如, execFile('C:/helloworld.py')

execFile('helloworld.py') does the job for me. A thing to note is to enter the complete directory name of the .py file if it isnt in the Python folder itself (atleast this is the case on Windows)

For example, execFile('C:/helloworld.py')


回答 5

最简单的方法

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3

EASIEST WAY

python -i helloworld.py  #Python 2

python3 -i helloworld.py #Python 3

回答 6

例如:

import subprocess

subprocess.call("C:\helloworld.py")

subprocess.call(["python", "-h"])

For example:

import subprocess

subprocess.call("C:\helloworld.py")

subprocess.call(["python", "-h"])

回答 7

在Python 3中,没有execFile。一个可以使用exec内置函数,例如:

import helloworld
exec('helloworld')

In Python 3, there is no execFile. One can use exec built-in function, for instance:

import helloworld
exec('helloworld')

回答 8

在IDLE中,以下工作:

import helloworld

我对它为什么起作用并不十分了解,但是它确实起作用。

In IDLE, the following works :-

import helloworld

I don’t know much about why it works, but it does..


回答 9

要在python外壳程序(例如Idle)或Django外壳程序中运行python脚本,您可以使用exec()函数执行以下操作。Exec()执行代码对象参数。Python中的代码对象就是简单地编译的Python代码。因此,您必须首先编译脚本文件,然后使用exec()执行它。从您的外壳:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

我正在使用Python 3.4。有关详细信息,请参见compileexec文档。

To run a python script in a python shell such as Idle or in a Django shell you can do the following using the exec() function. Exec() executes a code object argument. A code object in Python is simply compiled Python code. So you must first compile your script file and then execute it using exec(). From your shell:

>>>file_to_compile = open('/path/to/your/file.py').read()
>>>code_object = compile(file_to_compile, '<string>', 'exec')
>>>exec(code_object)

I’m using Python 3.4. See the compile and exec docs for detailed info.


回答 10

我对此进行了测试,并且可以解决:

exec(open('filename').read())  # Don't forget to put the filename between ' '

I tested this and it kinda works out :

exec(open('filename').read())  # Don't forget to put the filename between ' '

回答 11

你可以通过两种方式做到

  • import file_name

  • exec(open('file_name').read())

但请确保该文件应存储在程序运行的位置

you can do it by two ways

  • import file_name

  • exec(open('file_name').read())

but make sure that file should be stored where your program is running


回答 12

在Windows环境中,您可以使用以下语法在Python3 Shell命令行上执行py文件:

exec(open(’file_name的绝对路径’).read())

下面说明了如何从python shell命令行执行简单的helloworld.py文件

文件位置:C:/Users/testuser/testfolder/helloworld.py

文件内容:print(“ hello world”)

我们可以在Python3.7 Shell上执行以下文件:

>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'

>>> exec(open("helloworld.py").read())
hello world

>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world

>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world

On Windows environment, you can execute py file on Python3 shell command line with the following syntax:

exec(open(‘absolute path to file_name’).read())

Below explains how to execute a simple helloworld.py file from python shell command line

File Location: C:/Users/testuser/testfolder/helloworld.py

File Content: print(“hello world”)

We can execute this file on Python3.7 Shell as below:

>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'

>>> exec(open("helloworld.py").read())
hello world

>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world

>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world

回答 13

还有另一种选择(适用于Windows)-

    import os
    os.system('py "<path of program with extension>"')

There is one more alternative (for windows) –

    import os
    os.system('py "<path of program with extension>"')

回答 14

在python控制台中,可以尝试以下2种方法。

在同一个工作目录下

1. >>导入helloworld

#如果您有变量x,则可以在IDLE中将其打印出来。

>> helloworld.x

#如果您具有函数func,则也可以这样调用它。

>> helloworld.func()

2. >> runfile(“ ./ helloworld.py”)

In a python console, one can try the following 2 ways.

under the same work directory,

1. >> import helloworld

# if you have a variable x, you can print it in the IDLE.

>> helloworld.x

# if you have a function func, you can also call it like this.

>> helloworld.func()

2. >> runfile(“./helloworld.py”)