标签归档:shell

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

如何逃避os.system()调用?

问题:如何逃避os.system()调用?

使用os.system()时,通常必须转义文件名和其他作为参数传递给命令的参数。我怎样才能做到这一点?最好是可以在多个操作系统/ shell上运行的东西,尤其是bash。

我目前正在执行以下操作,但是请确保为此必须有一个库函数,或者至少是一个更优雅/更强大/更有效的选项:

def sh_escape(s):
   return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")

os.system("cat %s | grep something | sort > %s" 
          % (sh_escape(in_filename), 
             sh_escape(out_filename)))

编辑:我已经接受了使用引号的简单答案,不知道为什么我没有想到它;我猜是因为我来自Windows,“和”的行为略有不同。

关于安全性,我理解这个问题,但是在这种情况下,我对os.system()提供的一种快速简便的解决方案感兴趣,并且字符串的来源不是用户生成的,或者至少是由受信任的用户(我)。

When using os.system() it’s often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.

I’m currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:

def sh_escape(s):
   return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ")

os.system("cat %s | grep something | sort > %s" 
          % (sh_escape(in_filename), 
             sh_escape(out_filename)))

Edit: I’ve accepted the simple answer of using quotes, don’t know why I didn’t think of that; I guess because I came from Windows where ‘ and ” behave a little differently.

Regarding security, I understand the concern, but, in this case, I’m interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).


回答 0

这是我用的:

def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"

外壳程序将始终接受带引号的文件名,并在将其传递给相关程序之前删除引号。值得注意的是,这避免了文件名包含空格或其他任何讨厌的shell元字符的问题。

更新:如果您使用的是Python 3.3或更高版本,请使用shlex.quote而不是自己滚动。

This is what I use:

def shellquote(s):
    return "'" + s.replace("'", "'\\''") + "'"

The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter.

Update: If you are using Python 3.3 or later, use shlex.quote instead of rolling your own.


回答 1

shlex.quote() 从python 3开始做你想要的事情。

(用于pipes.quote同时支持python 2和python 3)

shlex.quote() does what you want since python 3.

(Use pipes.quote to support both python 2 and python 3)


回答 2

也许您有使用的特定原因os.system()。但是,如果不是这样,您可能应该使用该subprocess模块。您可以直接指定管道,并避免使用外壳。

以下是来自PEP324的内容

Replacing shell pipe line
-------------------------

output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

Perhaps you have a specific reason for using os.system(). But if not you should probably be using the subprocess module. You can specify the pipes directly and avoid using the shell.

The following is from PEP324:

Replacing shell pipe line
-------------------------

output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

回答 3

也许subprocess.list2cmdline是更好的选择?

Maybe subprocess.list2cmdline is a better shot?


回答 4

请注意,pipes.quote实际上在Python 2.5和Python 3.1中已损坏,并且不安全使用-它不处理零长度参数。

>>> from pipes import quote
>>> args = ['arg1', '', 'arg3']
>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))
mycommand arg1  arg3

参见Python问题7476 ; 它已在Python 2.6和3.2及更高版本中修复。

Note that pipes.quote is actually broken in Python 2.5 and Python 3.1 and not safe to use–It doesn’t handle zero-length arguments.

>>> from pipes import quote
>>> args = ['arg1', '', 'arg3']
>>> print 'mycommand %s' % (' '.join(quote(arg) for arg in args))
mycommand arg1  arg3

See Python issue 7476; it has been fixed in Python 2.6 and 3.2 and newer.


回答 5

注意:这是Python 2.7.x的答案。

根据消息来源,这pipes.quote()是“ 可靠地将字符串作为/ bin / sh的单个参数引用 ”的一种方法。(尽管从2.7版开始不推荐使用,但最终在Python 3.3中公开公开为shlex.quote()函数。)

另一方面subprocess.list2cmdline()是一种方法,“ 翻译的参数的序列到命令行串,使用同样的规则作为MS C运行时 ”。

在这里,我们为平台提供了引用命令行字符串的方式。

import sys
mswindows = (sys.platform == "win32")

if mswindows:
    from subprocess import list2cmdline
    quote_args = list2cmdline
else:
    # POSIX
    from pipes import quote

    def quote_args(seq):
        return ' '.join(quote(arg) for arg in seq)

用法:

# Quote a single argument
print quote_args(['my argument'])

# Quote multiple arguments
my_args = ['This', 'is', 'my arguments']
print quote_args(my_args)

Notice: This is an answer for Python 2.7.x.

According to the source, pipes.quote() is a way to “Reliably quote a string as a single argument for /bin/sh“. (Although it is deprecated since version 2.7 and finally exposed publicly in Python 3.3 as the shlex.quote() function.)

On the other hand, subprocess.list2cmdline() is a way to “Translate a sequence of arguments into a command line string, using the same rules as the MS C runtime“.

Here we are, the platform independent way of quoting strings for command lines.

import sys
mswindows = (sys.platform == "win32")

if mswindows:
    from subprocess import list2cmdline
    quote_args = list2cmdline
else:
    # POSIX
    from pipes import quote

    def quote_args(seq):
        return ' '.join(quote(arg) for arg in seq)

Usage:

# Quote a single argument
print quote_args(['my argument'])

# Quote multiple arguments
my_args = ['This', 'is', 'my arguments']
print quote_args(my_args)

回答 6

我相信os.system只会调用为用户配置的任何命令外壳,因此我认为您不能以与平台无关的方式进行操作。我的命令外壳可以是bash,emacs,ruby甚至quake3中的任何东西。这些程序中的某些程序并不期望您传递给它们的参数的种类,即使它们这样做了,也无法保证它们以相同的方式进行转义。

I believe that os.system just invokes whatever command shell is configured for the user, so I don’t think you can do it in a platform independent way. My command shell could be anything from bash, emacs, ruby, or even quake3. Some of these programs aren’t expecting the kind of arguments you are passing to them and even if they did there is no guarantee they do their escaping the same way.


回答 7

我使用的功能是:

def quote_argument(argument):
    return '"%s"' % (
        argument
        .replace('\\', '\\\\')
        .replace('"', '\\"')
        .replace('$', '\\$')
        .replace('`', '\\`')
    )

即:我总是将参数用双引号引起来,然后用反斜杠将双引号内的特殊字符引起来。

The function I use is:

def quote_argument(argument):
    return '"%s"' % (
        argument
        .replace('\\', '\\\\')
        .replace('"', '\\"')
        .replace('$', '\\$')
        .replace('`', '\\`')
    )

that is: I always enclose the argument in double quotes, and then backslash-quote the only characters special inside double quotes.


回答 8

如果您确实使用了system命令,我将尝试将os.system()调用中的内容列入白名单。

clean_user_input re.sub("[^a-zA-Z]", "", user_input)
os.system("ls %s" % (clean_user_input))

子进程模块是一个更好的选择,我建议尽量避免使用os.system / subprocess之类的东西。

If you do use the system command, I would try and whitelist what goes into the os.system() call.. For example..

clean_user_input re.sub("[^a-zA-Z]", "", user_input)
os.system("ls %s" % (clean_user_input))

The subprocess module is a better option, and I would recommend trying to avoid using anything like os.system/subprocess wherever possible.


回答 9

真正的答案是:首先不要使用os.system()。请subprocess.call改用并提供未转义的参数。

The real answer is: Don’t use os.system() in the first place. Use subprocess.call instead and supply the unescaped arguments.


Shell脚本与Python相比的优势[关闭]

问题:Shell脚本与Python相比的优势[关闭]

我尝试了几次学习shell(bash)脚本的过程,但是却被语法所取代。然后,我找到了Python,并且能够完成Shell脚本可以在Python中完成的大部分工作。我现在不确定是否应该再花时间在学习shell脚本上了。所以我想问:

与Python相比,shell脚本有哪些优势使其成为必不可少的工具?

我不是专业的系统管理人员,但是我对为家庭用户设置Linux系统感兴趣,因此我认为学习Shell脚本可能变得必要。

I tried to learn shell(bash) scripting few times but was driven away by the syntax. Then I found Python and was able to do most of the things a shell script can do in Python. I am now not sure whether I should invest my time in learning shell scripting anymore. So I want to ask:

What are strengths of shell scripting that make it an indispensable tool as compared to Python?

I am not a system administration by profession, but I am interested in setting up Linux systems for home users, hence I think learning shell scripting can become necessary.


回答 0

  • Shell脚本具有用于I / O重定向的更简单的表示法。
  • 从Shell中的现有程序创建管道更简单。
  • Shell脚本重用了整个程序。
  • Shell是通用的(在Unix之类的东西上)-不一定要安装Python。

“的确,您可以在Python中完成所有可以在Shell中完成的工作;同样,在Python中有些容易实现的事情在外壳中很难实现(就像有些东西在Shell中实现容易但在Python中很难实现一样)。从长远来看,了解两者将是最好的。

  • Shell scripting has simpler notations for I/O redirection.
  • It is simpler to create pipelines out of existing programs in shell.
  • Shell scripting reuses entire programs.
  • Shell is universally available (on anything like Unix) – Python is not necessarily installed.

‘Tis true that you can do everything in Python that you can do in shell; ’tis also true that there are things that are easy in Python that are hard in shell (just as there are things that are easy in shell but hard in Python). Knowing both will be best in the long term.


回答 1

“与Python相比,shell脚本有什么优势使其成为必不可少的工具?”

外壳不是必不可少的。您为什么认为有这么多?bash,tcsh,csh,sh等,等等,

Python 一个外壳。这不是理想的运行脚本,而不是用于运行所有命令的脚本。

Python是所有Linux发行版中的或多或少的标准部分。

更传统的外壳会做很多事情。

  1. 他们有一个方便的用户界面来运行命令。这包括单行命令,shell在其中搜索您的PATH,派生并执行所请求的程序。它还包括管道,序列和并发程序(使用;|&),以及一些重定向(使用><)。

  2. 它们具有运行脚本的简陋的类似于编程语言的功能。这种语言很难使用,效率极低。这种语言的大多数语句都需要分叉一个或多个其他过程,从而浪费时间和内存。

从shell运行程序,将stderr重定向到日志文件,这样的事情就很好了。在外壳中执行该操作。

作为Python脚本,几乎所有其他内容都可以更高效,更清晰地完成。

你们两个都需要。但是,永远不要使用传统的外壳语言编写带有if语句或循环的脚本。

“What are strengths of shell scripting that make it an indispensable tool as compared to Python?”

The shell is not indispensable. Why do you think there are so many? bash, tcsh, csh, sh, etc., etc.,

Python is a shell. Not the one you’d use for running all commands, but for scripting, it’s ideal.

Python is a more-or-less standard part of all Linux distro’s.

The more traditional shells do too many things.

  1. They have a handy user interface for running commands. This includes one-line commands where the shell searches your PATH, forks and execs the requested program. It also includes pipelines, sequences and concurrent programs (using ;, | and &) as well as some redirection (using > and <).

  2. They have a crummy little programming-language-like capability for running scripts. This language is rather hard to use and extremely inefficient. Most statements in this language require forking one or more additional processes, wasting time and memory.

Running programs from the shell, redirecting stderr to a log file and that kind of thing is good. Do that in the shell.

Almost everything else can be done more efficiently and more clearly as a Python script.

You need both. However, you should never write a script with if-statements or loops in a traditional shell language.


回答 2

Shell使普通和简单的动作真正简单了,但代价是使更复杂的事情变得更加复杂。

通常,一个小的Shell脚本会比相应的python程序更短,更简单,但是python程序会趋于优雅地接受修改,而随着代码的添加,shell脚本的可维护性会越来越少。

这样的结果是,为了获得最佳的日常生产力,您需要shell脚本,但是您应该主要将其用于一次性脚本,并在其他地方使用python。

The shell makes common and simple actions really simple, at the expense of making more complex things much much more complex.

Typically, a small shell script will be shorter and simpler than the corresponding python program, but the python program will tend to gracefully accept modifications, whereas the shell script will tend to get less and less maintainable as code is added.

This has the consequence that for optimal day-to-day productivity you need shell-scripting, but you should use it mostly for throwaway scripts, and use python everywhere else.


回答 3

Shell脚本无可比拟,而Python则无能为力。Shell脚本的最大优点是,您使用的命令与使用Shell时使用的命令相同,因此,如果您是大量Shell用户,则Shell脚本有时会成为一种非常快速简便的方法来自动执行Shell工作。

我也发现在shell脚本中处理数据管道比在python中更容易,尽管它在python中绝对可行。

最后,您不必启动其他干扰程序即可运行Shell脚本,从而为您提供了非常小但有时可能在速度和内存使用方面的明显优势。

但是话又说回来,Python脚本更具可维护性,因此我正试图从大型的难看的Shell脚本迁移到Python脚本。使用Python进行异常处理和质量检查也更加容易。

There’s nothing you can do with shell scripts that you can’t do with python. The big advantage of shell scripts is that you use the same commands as you do when you use the shell, so if you’re a heavy shell user, shell scripting will at some point become a very quick and easy way to automate your shell work.

I also find it easier to deal with pipes of data in shell scripts than in python, though it’s absolutely doable from python.

And, finally, you don’t have to fire up an additional interpeter to run the shell scripts, giving you a very small, but sometimes maybe noticeable speed and memory usage advantage.

But then again, Python scripts are a lot more maintainable, I’m trying to migrate from big ugly shell scripts to Python scripts for that very reason. It’s also easier to do exception handling and QA with Python.


回答 4

前面的所有答案都表明,不必学习shell脚本。但是学习永远不是一件坏事。这实际上是个人优先级的问题。别人很难告诉您什么是不值得的。

大多数程序员发现,每次学习新语言都会变得越来越容易。(自然语言也是如此。)并且越早开始越好。

加:学习了一门语言,使您可以从完全的知识和熟悉的位置上摆脱它的局限性。这可能不会让你被解雇,但是可能会从同龄人那里获得啤酒!

one doesn’t have to learn shell scripting, as all the previous answers indicate; but learning is never a bad thing. it’s really a question of personal priorities. it’s very hard for someone else to tell you what is and isn’t worth your time.

most programmers find that learning new languages gets incrementally easier each time. (the same is largely true of natural languages too.) and the earlier you start, the better.

plus: having learned a language enables you to extravagantly diss its limitations from a position of complete knowledge and familiarity. this probably won’t get you laid, but might earn you a beer from your peers!


回答 5

我同意以前的大多数答案。我认为Shell命令最适合执行面向文件系统的任务(复制和移动文件,grep等)。我认为,如果您必须读写文件,那么Shell会更好,因为单个>>file.txt重定向会立即添加到文件中,而不是像file=open('file.txt','a'); file.write()等等。

目前,出于个人用途,我混合了两种方法,分别是创建一个python脚本,然后每次在shell中比在python中更容易执行某个操作时就调用os.system(’command’)或os.popen(’command’)。

I agree with most of the previous answers. I consider shell commands most suited to do filesystem-oriented tasks (copy and move files, grep, etc). Shell is better, in my opinion, if you have to read and write to file, since a single >>file.txt redirection appends to file instantly, instead of needing, say, file=open('file.txt','a'); file.write(), etc.

Currently, for my personal use, I mix both, creating a python script and calling os.system(‘command’) or os.popen(‘command’) every time some action is easier in shell than in python.


回答 6

该外壳随处可见。如果您坚持使用一套相对基本的可移植功能,则您的脚本可以在手机,无线路由器,DVR,上网本,工作站,大型钢铁服务器等上运行。在许多系统上,Python不一定是开箱即用的,根据环境的不同,可能很难安装它。

学习一些shell脚本也可以帮助您学习一些命令行技巧,因为命令行是shell。这对于采取一些相当长且复杂的命令行,并在您意识到您将需要更多的命令行之后将其转换为更通用的脚本也很有用。

该外壳还具有一些非常强大的功能。据我所知,管道是一个非常有趣的控制结构,仅对外壳是本地的。

The shell is available everywhere. If you stick to a relatively basic set of portable functionality, your scripts can run on cell phones, wireless routers, DVRs, netbooks, workstations, big iron servers, and the like. Python is not necessarily included out of the box on lots of systems, and depending on the environment it may be hard to get it installed.

Learning some shell scripting can also help you learn some command line tricks, since the command line is, well, the shell. It’s also good for taking some fairly long and complicated command line, and converting that into a more general script after you realize you’ll need it some more.

The shell also has some pretty powerful features; pipelines are a really interesting control construct that is native only to the shell, as far as I know.


回答 7

选择Python的Shell脚本时要考虑的另一件事是将在目标计算机上运行的Python版本。RHEL5(仅举一例)将存在很长时间。RHEL5停留在Python 2.4中。有很多不错的库,它们依赖于2.4后的Python添加的功能。

Another thing to consider when choosing shell scripts of Python is the Python version that will be running on the target machines. RHEL5 (to name one) is going to be around for a long time. RHEL5 is stuck with Python 2.4. There are a lot of nice libraries that depend on functionality added to Python post-2.4.


如何在PyCharm终端中激活virtualenv?

问题:如何在PyCharm终端中激活virtualenv?

我已经设置了PyCharm,创建了我的virtualenv(通过virtual env命令,或者直接在PyCharm中),并将那个环境激活为我的解释器。一切正常。

但是,如果我使用“工具,打开终端”打开终端,则提供的shell提示使用虚拟环境。我仍然必须source ~/envs/someenv/bin/activate在该终端内使用才能激活它。

另一种方法是在外壳中激活环境,然后从该环境运行PyCharm。这是“可行的”但很丑陋,这意味着如果我从PyCharm切换环境或项目,我会遇到重大问题:我现在使用的是完全错误的环境。

还有其他更简便的方法来使“工具,打开终端”自动激活虚拟环境吗?

I’ve set up PyCharm, created my virtualenv (either through the virtual env command, or directly in PyCharm) and activated that environment as my Interpreter. Everything is working just fine.

However, if I open a terminal using “Tools, Open Terminal”, the shell prompt supplied is not using the virtual env; I still have to use source ~/envs/someenv/bin/activate within that Terminal to activate it.

Another method is to activate the environment in a shell, and run PyCharm from that environment. This is “workable” but pretty ugly, and means I have major problems if I switch environments or projects from PyCharm: I’m now using the totally-wrong environment.

Is there some other, much-easier way to have “Tools, Open Terminal” automatically activate the virtual environment?


回答 0

编辑:

根据https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal的介绍,PyCharm 2016.3(于2016年11月发布)具有开箱即用的virutalenv支持

bash,zsh,fish和Windows cmd支持自动virtualenv。您可以在“设置”(“首选项”)|“自定义”中自定义外壳首选项。工具| 终奌站。


旧方法:

.pycharmrc在主文件夹中创建一个包含以下内容的文件

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

Edit:

According to https://www.jetbrains.com/pycharm/whatsnew/#v2016-3-venv-in-terminal, PyCharm 2016.3 (released Nov 2016) has virutalenv support for terminals out of the box

Auto virtualenv is supported for bash, zsh, fish, and Windows cmd. You can customize your shell preference in Settings (Preferences) | Tools | Terminal.


Old Method:

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

回答 1

更新:

设置(首选项)|首选项中的首选项 工具| 终端是全球性的。
如果为每个项目使用venv,请记住使用当前路径变量和默认venv名称:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

对于Windows用户:在虚拟环境中使用PyCharm时,可以使用该/K参数cmd.exe自动设置虚拟环境。

PyCharm 3或4: ,,Settings 和添加。TerminalDefault shell/K <path-to-your-activate.bat>

PyCharm 5: ,SettingsToolsTerminal并添加/K <path-to-your-activate.bat>Shell path

PyCharm 2016.1或2016.2: ,SettingsToolsTerminal并添加""/K <path-to-your-activate.bat>""Shell path,并添加(介意引号)。还要在cmd.exe周围加上引号,导致:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""

Update:

The preferences in Settings (Preferences) | Tools | Terminal are global.
If you use a venv for each project, remember to use current path variable and a default venv name:

"cmd.exe" /k ""%CD%\venv\Scripts\activate"" 

For Windows users: when using PyCharm with a virtual environment, you can use the /K parameter to cmd.exe to set the virtual environment automatically.

PyCharm 3 or 4: Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

PyCharm 5: Settings, Tools, Terminal, and add /K <path-to-your-activate.bat> to Shell path.

PyCharm 2016.1 or 2016.2: Settings, Tools, Terminal, and add ""/K <path-to-your-activate.bat>"" to Shell path and add (mind the quotes). Also add quotes around cmd.exe, resulting in:

"cmd.exe" /k ""C:\mypath\my-venv\Scripts\activate.bat""


回答 2

对于Windows用户,在Windows下使用PyCharm和虚拟环境时,可以使用/ k参数cmd.exe来自动设置虚拟环境。

转到“设置”,“终端”,“默认外壳”并添加/K <path-to-your-activate.bat>

我没有对早期回复发表评论的声誉,因此请发布此更正版本。这确实节省了很多时间。

更新:

注意:Pycharm现在直接支持虚拟环境,对我来说似乎很好用-因此不再需要我的解决方法。

For Windows users when using PyCharm and a virtual environment under Windows, you can use the /k parameter to cmd.exe to set the virtual environment automatically.

Go to Settings, Terminal, Default shell and add /K <path-to-your-activate.bat>.

I don’t have the reputation to comment on the earlier response so posting this corrected version. This really saves a LOT of time.

Update:

Note: Pycharm now supports virtual environments directly and it seems to work well for me – so my workaround not needed anymore.


回答 3

根据彼得的回答和实验,我提出了一个很好的“一般解决方案”,可以解决以下问题:

  • 恢复登录外壳程序的行为。PyCharm通常运行登录外壳程序,但是–rcfile阻止了这种情况的发生。脚本仍然使用–rcfile,但是尝试模拟登录shell的INVOCATION行为。
  • 无需为每个环境创建rcfile
  • 如果您更改环境,则无需更新项目设置。

将此脚本放入bin目录中的某个位置。例如〜/ bin / pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

然后将PyCharm的Shell路径设置为:

/bin/bash --rcfile ~/bin/pycharmactivate

Based on answers from Peter and experimentation, I’ve come up with a good “general solution”, which solves the following:

  • Restores the behaviour of a login shell. PyCharm normally runs a login shell, but –rcfile stopped this happening. Script still uses –rcfile, but attempts to emulate the INVOCATION behaviour of a login shell.
  • Removes the need to create an rcfile for each environment
  • Removes the need to update the project settings if you change the environment.

Drop this script into a bin directory somewhere. E.g. ~/bin/pycharmactivate

if [ -r "/etc/profile" ] ; then . /etc/profile ; fi
if [ -r "~/.bash_profile" ] ; then
    . ~/.bash_profile
elif [ -r "~/.bash_login" ] ; then
    . ~/.bash_login
elif [ -r "~/.profile" ] ; then
    . ~/.profile
fi
ACTIVATERC=`cat .idea/workspace.xml | perl -n -e 'print "\$1/bin/activate" if m:option name="SDK_HOME" value="\\\$USER_HOME\\\$(.*)/bin/python":'`
if [ -n "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; else echo "Could not find virtualenv from PyCharm" ; fi

Then set PyCharm’s Shell path to:

/bin/bash --rcfile ~/bin/pycharmactivate

回答 4

PyCharm 4现在在IDE中集成了virtualenvs。选择项目解释器时,可以创建,添加或选择一个virtualenv。他们添加了一个在配置的项目解释器中运行的“ Python控制台”。

更多信息在这里。

PyCharm 4 now has virtualenvs integrated in the IDE. When selecting your project interpreter, you can create, add, or select a virtualenv. They’ve added a “Python Console” that runs in the configured project interpreter.

More info here.


回答 5

谢谢克里斯,您的脚本适用于某些项目,但不是我的机器上的全部。这是我编写的脚本,希望任何人都觉得它有用。

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi

回答 6

我已经查看了上面所有的答案,但是没有一个对我来说足够优雅。在Pycharm 2017.1.3(在我的计算机中)中,最简单的方法是打开Settings->Tools->Terminal并检查Shell integrationActivate virtualenv选项。

I have viewed all of the answers above but none of them is elegant enough for me. In Pycharm 2017.1.3(in my computer), the easiest way is to open Settings->Tools->Terminal and check Shell integration and Activate virtualenv options.


回答 7

如果您使用的是Windows版本,则非常简单。如果您已经拥有虚拟环境,则只需导航至其文件夹,然后在文件夹activate.bat内找到即可Scripts。复制它的完整路径,并将其粘贴到pycharm的终端中,然后按Enter完成。

如果您需要创建新的虚拟环境:

转到“文件”>“设置”,然后搜索project interpreter,打开,单击齿轮按钮并在所需的位置创建环境,然后按照第一段进行操作。

If You are using windows version it is quite easy. If you already have the virtual environment just navigate to its folder, find activate.bat inside Scripts folder. copy it’s full path and paste it in pycharm’s terminal then press Enter and you’re done!

If you need to create new virtual environment :

Go to files > settings then search for project interpreter, open it, click on gear button and create the environment wherever you want and then follow first paragraph.


回答 8

在Mac上,它是PyCharm => Preferences … => Tools => Terminal => Activate virtualenv,默认情况下应启用。

On Mac it’s PyCharm => Preferences… => Tools => Terminal => Activate virtualenv, which should be enabled by default.


回答 9

我刚刚在主目录中添加了一个名为pycharmactivate的脚本。设置PyCharm(4.0.1)文件>设置>工具>终端> / bin / bash –rcfile〜/ pycharmactivate的Shell路径的值。如果您有不同的项目和virtualenv目录/名称,也许不是最好的解决方案,但是它对我有用。该脚本包含以下3行,并假定您的virtualenv与项目目录具有相同的名称。

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

I just added a script named pycharmactivate to my home directory. Set value of PyCharm (4.0.1) File > Settings > Tools > Terminal > Shell path to /bin/bash –rcfile ~/pycharmactivate. Maybe not the best solution incase you have different project and virtualenv directories/names but it works for me. This script contains the following 3 lines and assumes your virtualenv has the same name as your project dir.

source ~/.bashrc
projectdir=${PWD##*/}
source ~/.virtualenvs/$projectdir/bin/activate

回答 10

跟进Peter的回答,这里是.pycharmrc文件的Mac版本:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

母鸡

Following up on Peter’s answer, here the Mac version of the .pycharmrc file:

source /etc/profile
source ~/.bash_profile
source  <venv_dir>/bin/activate

Hen


回答 11

我有一个可以在Windows 7计算机上使用的解决方案。

我相信PyCharm的终端是它运行的结果,它将cmd.exe加载Windows PATH变量,并使用在其中首先找到的Python版本PATH。要编辑此变量,请右键单击我的电脑 -> 属性 -> 高级系统设置 -> 高级选项卡-> 环境变量…按钮。在“ 系统变量”部分中,选择并编辑PATH变量。

这是我编辑PATH 之前的相关部分:

C:\ Python27 \;
C:\ Python27 \ Lib \ site-packages \ pip \;
C:\ Python27 \ Scripts;
C:\ Python27 \ Lib \ site-packages \ django \ bin;

…并且编辑PATH(现在仅3行):

C:[project_path] \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ pip;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Scripts;
C:[project_path] \ virtualenvs \ virtualenv-Py2.7_Dj1.7 \ Lib \ site-packages \ django \ bin;

要测试这一点,请打开一个新的 Windows终端(开始 ->键入cmd并点击Enter),看看它是否正在使用您的虚拟环境。如果可行,请重新启动PyCharm,然后在PyCharm的终端中对其进行测试。

I have a solution that worked on my Windows 7 machine.

I believe PyCharm’s terminal is a result of it running cmd.exe, which will load the Windows PATH variable, and use the version of Python that it finds first within that PATH. To edit this variable, right click My Computer –> Properties –> Advanced System Settings –> Advanced tab –> Environment Variables… button. Within the System variables section, select and edit the PATH variable.

Here is the relevant part of my PATH before editing:

C:\Python27\;
C:\Python27\Lib\site-packages\pip\;
C:\Python27\Scripts;
C:\Python27\Lib\site-packages\django\bin;

…and after editing PATH (only 3 lines now):

C:[project_path]\virtualenv-Py2.7_Dj1.7\Lib\site-packages\pip;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Scripts;
C:[project_path]\virtualenvs\virtualenv-Py2.7_Dj1.7\Lib\site-packages\django\bin;

To test this, open a new windows terminal (Start –> type in cmd and hit Enter) and see if it’s using your virtual environment. If that works, restart PyCharm and then test it out in PyCharm’s terminal.


回答 12

这就是我在做什么:在源代码文件夹中创建一个activate_env.bat(在Linux中为Windows,也许是.sh)文件:

/env_yourenvlocate/scripts/activate.bat

和另一个文件deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

每次打开终端窗口时,只需执行bat文件来激活/停用virtualenv,您将停留在源代码路径中,而无需更改路径。

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

this is what i am doing: create a activate_env.bat(windows,maybe .sh in linux) file in the source code folde:

/env_yourenvlocate/scripts/activate.bat

and another file deactivate_env.bat:

/env_yourenvlocate/scripts/deactivate.bat

everytime open the terminal window, just execute the bat file to activate/deactivate the virtualenv, you will stay in source code path, no need to change path to and back.

E:\Projects\django_study\src>active_env.bat

E:\Projects\django_study\src>../env_django_study/scripts/activate.bat
(env_django_study) E:\Projects\django_study\src>



(env_django_study) E:\Projects\django_study\src>deactive_env.bat

(env_django_study)E:\Projects\django_study\src>../env_django_study/scripts/deactivate.bat
E:\Projects\django_study\src>

回答 13

如果您的Pycharm 2016.1.4v及更高版本应使用 "default path" /K "<path-to-your-activate.bat>" 不要忘记引号

If your Pycharm 2016.1.4v and higher you should use "default path" /K "<path-to-your-activate.bat>" don’t forget quotes


回答 14

如果您已将项目移动到另一个目录,则可以通过“设置”对话框设置新路径。然后,您需要在“编辑配置”对话框中设置此项目解释器。

If you have moved your project to another directory, you can set the new path via Settings dialog. And then you need to set this Project Interpreter in the Edit Configuration dialog.


回答 15

另一种选择是使用virtualenvwrapper来管理您的虚拟环境。看来,一旦virtualenvwrapper 脚本被激活,pycharm就可以使用它,然后workon从pycharm控制台可以使用简单的命令,并为您提供可用的虚拟环境:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

Another alternative is to use virtualenvwrapper to manage your virtual environments. It appears that once the virtualenvwrapper script is activated, pycharm can use that and then the simple workon command will be available from the pycharm console and present you with the available virtual environments:

kevin@debian:~/Development/django-tutorial$ workon
django-tutorial
FlaskHF
SQLAlchemy
themarkdownapp
kevin@debian:~/Development/django-tutorial$ workon django-tutorial
(django-tutorial)kevin@debian:~/Development/django-tutorial$ 

回答 16

该方法应该在每个项目的任意虚拟环境下都可以使用,并且由于使用创建的钩子,因此不会对您的环境做任何假设。

你写:

  • 调用钩子的全局脚本
  • 每个PyCharm项目的挂钩脚本(不是必需的)

鉴于当前最新的PyCharm(社区2016.1)不允许每个项目的终端设置都调用项目特定挂钩的脚本开头。这是我的~/.pycharmrc

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

如果您使用的不是Bash,.bash_profile则应调用自己的等效项。

现在,将PyCharm设置为“工具->终端->外壳路径”以调用此脚本,例如: /bin/bash --rcfile ~/.pycharmrc

最后,对于每个PyCharm项目,您都需要激活特定的虚拟环境,请在PyCharm项目root内创建一个文件.pycharm/term-activate。这是您的钩子,它将仅为您的PyCharm项目定义所需的虚拟环境的名称:

export PYCHARM_VENV=<your-virtual-env-name>

当然,您可以使用在您的特定PyCharm项目的终端环境中发现有用的任何东西来扩展自己的功能。

This method should work with arbitrary virtual environments per project and it doesn’t make assumptions on your environment as it is using hooks you create.

You write:

  • A global script that invokes the hook
  • A hook script per PyCharm project (not mandatory)

Given that the current latest PyCharm (Community 2016.1) does not allow for Terminal settings per project start with the script that invokes the project specific hook. This is my ~/.pycharmrc:

if [ -r ".pycharm/term-activate" ]; then
   echo "Terminal activation hook detected."
   echo "Loading Bash profile..."
   source ~/.bash_profile
   echo "Activating terminal hook..."
   source ".pycharm/term-activate"
   source activate $PYCHARM_VENV
fi

If you are using something other than Bash, invoke your own .bash_profile equivalent should you wish to.

Now set your PyCharm “Tools -> Terminal -> Shell Path” to invoke this script, e.g.: /bin/bash --rcfile ~/.pycharmrc

Finally, for every PyCharm project you need a specific virtual environment activated, create a file within the PyCharm project root .pycharm/term-activate. This is your hook and it will simply define the name of the desired virtual environment for your PyCharm project:

export PYCHARM_VENV=<your-virtual-env-name>

You can of course extend your hooks with anything you find useful in the terminal environment of your particular PyCharm project.


回答 17

对于Windows上的conda虚拟环境,请确保未命名您的批处理文件,activate.bat因为这将导致与conda activate命令冲突,从而导致对该批处理文件的递归调用。

下面的Shell路径对我有用:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

并在activate-env.bat文件中:

call activate myenvname

For conda virtual environments on Windows, make sure your batch file is NOT named activate.bat as this will cause a conflict with the conda activate command, resulting in a recursive calling of the batch file.

What works for me is the following Shell path:

"cmd.exe" /k ""C:\FullPathToYourProject\activate-env.bat""

And in the activate-env.bat file:

call activate myenvname

回答 18

我希望为每个项目提供一个单独的虚拟环境,并且不太在乎是否需要其他文件来简化此工作。您只需执行一次即可用于所有项目的解决方案,然后将以下内容添加到您的.bashrc或中.bash_profile

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

这将检查是否存在打开终端的虚拟环境,是否激活了终端(当然可以使用其他相对路径)。PyCharm的终端设置可以保留为默认设置。

I wanted a separate virtual environment for each project, and didn’t care much for having additional files to facilitate this. A solution which you only need to do once and works for all projects is then adding the following to your .bashrc or .bash_profile:

if [ -d "./venv" ]; then
    source ./venv/bin/activate
fi

This checks if there is a virtual environment where the terminal is being opened, and if so activates it (and of course other relative paths could be used). PyCharm’s terminal settings can be left as their default.


回答 19

PyCharm 4.5.4

使用以下内容在主文件夹中创建文件.pycharmrc

source ~/.bashrc
source ~/pycharmvenv/bin/activate

使用您的virtualenv路径作为最后一个参数。

然后将Shell Preferences-> Project Settings-> Shell path设置为

/bin/bash --rcfile ~/.pycharmrc

我不知道为什么,但这对我不起作用。PyCharm打印错误。

cmd.exe /K "<path-to-your-activate.bat>" 它可以工作,但是即使没有必要,它也会为每个项目创建相同的virtualenv。

收据有效!但是字符串/env_yourenvlocate/scripts/activate.bat必须包含引号,像这样"Full_path_to_your_env_locate\scripts\activate.bat"

禁用virtualenv非常容易-在终端中输入’deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

PyCharm 4.5.4

Create a file .pycharmrc in your home folder with the following contents

source ~/.bashrc
source ~/pycharmvenv/bin/activate

Using your virtualenv path as the last parameter.

Then set the shell Preferences->Project Settings->Shell path to

/bin/bash --rcfile ~/.pycharmrc

I don’t why, but it doesn’t work for me. PyCharm prints an error.

cmd.exe /K "<path-to-your-activate.bat>" It works, but it creates the same virtualenv for each project, and even if this is not necessary.

This receipt is working! But the string /env_yourenvlocate/scripts/activate.bat must contain quotes, like this "Full_path_to_your_env_locate\scripts\activate.bat"!

Deactivate the virtualenv is very easy – type in the terminal ‘deactivate’

(virt_env) D:\Projects\src>deactivate
D:\Projects\src>

回答 20

WSL解决方案(Windows上的Ubuntu)

如果您使用的是WSL(在Windows上为Ubuntu),则还可以在pycharm中将bash作为终端打开,并激活linux virtualenv。

使用.pycharmrc类似于Peter Gibson答案中所述的文件;将.pycharmrc文件添加到您的主目录,其中包含以下内容:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

在Pycharm 文件>设置>工具>终端中,添加以下“外壳路径”:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


项目特定的virtualenv

您的virtualenv的路径.pycharmrc不必是绝对的。您可以通过在项目目录中设置相对路径来设置特定于项目的virtualenv。我的virtualenv始终位于项目目录下的“ venv”文件夹中,因此.pycharmrc文件如下所示:

来源〜/ .bashrc
源〜/ pycharmvenv / bin / activate#绝对路径
源./venv/bin/activate#相对路径


奖励:自动打开ssh隧道以将virtualenv连接为项目解释器

将以下内容添加到您的.pycharmrc文件中:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

这将检查ssh隧道是否已经打开,否则打开一个。在 Pycharm的“文件”->“设置”->“项目”->“项目解释器”中,添加具有以下配置的新远程解释器:

+ -------------------------- + ---------------------- ----------- + ------- + ---- +
| 名称:<口译员名称> | | |
| 选择| “ SSH凭证” | | |
| 主持人:127.0.0.1 | 端口:| 22 |
| 用户:| <Linux用户名> | | |
| 验证类型:| “密码” | | |
| 密码:<Linux密码> | | |
| Python解释器路径:<Linux到您的virtualenv的路径> | | |
| Python帮助程序路径:| <自动设置> | | |
+ -------------------------- + ---------------------- ----------- + ------- + ---- +

现在,当您打开项目时,bash会自动在virtualenv中启动,打开ssh隧道,并且pycharm将virtualenv连接为远程解释器。

警告:Windows中的最新更新将在启动时自动启动SshBroker和SshProxy服务。这些阻止了从Linux到Windows的ssh隧道。您可以在“任务管理器”->“服务”中停止这些服务,然后所有内容将再次运行。

Solution for WSL (Ubuntu on Windows)

If you’re using WSL (Ubuntu on Windows), you can also open bash as terminal in pycharm and activate a linux virtualenv.

Use a .pycharmrc file like described in Peter Gibson’s answer; Add the .pycharmrc file to your home directory with following content:

source ~/.bashrc
source ~/path_to_virtualenv/bin/activate

In Pycharm File > Settings > Tools > Terminal add the following ‘Shell path’:

"C:/Windows/system32/bash.exe" -c "bash --rcfile ~/.pycharmrc"


Project specific virtualenv

The path to your virtualenv in .pycharmrc does not have to be absolute. You can set a project specific virtualenv by setting a relative path from your project directory. My virtualenv is always located in a ‘venv’ folder under my project directory, so my .pycharmrc file looks like this:

source ~/.bashrc
source ~/pycharmvenv/bin/activate #absolute path
source ./venv/bin/activate #relative path


BONUS: automatically open ssh tunnel to connect virtualenv as project interpreter

Add the following to your .pycharmrc file:

if [ $(ps -aux | grep -c 'ssh') -lt 2 ]; then
    sudo service ssh start 
fi

This checks if a ssh tunnel is already opened, and opens one otherwise. In File -> Settings -> Project -> Project Interpreter in Pycharm, add a new remote interpreter with following configuration:

+--------------------------+---------------------------------+-------+----+
| Name:                    | <Interpreter name>              |       |    |
| Select                   | 'SSH Credentials'               |       |    |
| Host:                    | 127.0.0.1                       | Port: | 22 |
| User:                    | <Linux username>                |       |    |
| Auth type:               | 'Password'                      |       |    |
| Password:                | <Linux password>                |       |    |
| Python interpreter path: | <Linux path to your virtualenv> |       |    |
| Python helpers path:     | <Set automatically>             |       |    |
+--------------------------+---------------------------------+-------+----+

Now when you open your project, your bash automatically starts in your virtualenv, opens a ssh tunnel, and pycharm connects the virtualenv as remote interpreter.

warning: the last update in Windows automatically starts a SshBroker and SshProxy service on startup. These block the ssh tunnel from linux to windows. You can stop these services in Task Manager -> Services, after which everything will work again.


回答 21

输入终端>运行>调试>编辑配置时,您有一个选择

选择合适的conda环境。。同样,在创建新项目时-它要求配置该位置。

One option you have when you enter the terminal > Run > Debug > Edit Configurations

select the appropriate conda environmnent.. Also when you create a new project – it asks to configure this location.


为什么Python创建的MD5哈希与在外壳中使用echo和md5sum创建的MD5哈希不同?

问题:为什么Python创建的MD5哈希与在外壳中使用echo和md5sum创建的MD5哈希不同?

Python MD5哈希与shell上md5sum命令创建的哈希不同。为什么?

>>> import hashlib
>>> h = hashlib.md5()
>>> h.update("mystringforhash")
>>> print h.hexdigest()
86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python


$ echo mystringforhash | md5sum
686687dd68c5de717b34569dbfb8d3c3  - # Result on the shell

A Python MD5 hash is different than the one created by the md5sum command on the shell. Why?

>>> import hashlib
>>> h = hashlib.md5()
>>> h.update("mystringforhash")
>>> print h.hexdigest()
86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python


$ echo mystringforhash | md5sum
686687dd68c5de717b34569dbfb8d3c3  - # Result on the shell

回答 0

echo追加a,\n因为您通常不希望外壳中的行不以换行符结尾(如果提示不是从最左边开始,则看起来很丑)。
使用-n参数省略尾随的换行符,它将打印与您的python脚本相同的校验和:

> echo -n mystringforhash | md5sum
86b6423cb6d211734fc7d81bbc5e11d3  -

echo appends a \n since you usually do not want lines not ending with a linebreak in your shell (it looks really ugly if the prompt does not start at the very left).
Use the -n argument to omit the trailing linebreak and it will print the same checksum as your python script:

> echo -n mystringforhash | md5sum
86b6423cb6d211734fc7d81bbc5e11d3  -

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.


如何从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”)


如何检查scikit学习安装了哪个版本的nltk?

问题:如何检查scikit学习安装了哪个版本的nltk?

在shell脚本中,我正在检查是否已安装此软件包,如果未安装,请先安装它。因此,使用shell脚本:

import nltk
echo nltk.__version__

但它会在以下位置停止shell脚本 import在行

在Linux终端中尝试以这种方式查看:

which nltk

没有任何东西以为已安装。

还有没有其他方法可以在shell脚本中验证此软件包的安装,如果未安装,请同时安装。

In shell script I am checking whether this packages are installed or not, if not installed then install it. So withing shell script:

import nltk
echo nltk.__version__

but it stops shell script at import line

in linux terminal tried to see in this manner:

which nltk

which gives nothing thought it is installed.

Is there any other way to verify this package installation in shell script, if not installed, also install it.


回答 0

import nltk 是Python语法,因此无法在Shell脚本中使用。

为了测试的版本nltkscikit_learn,你可以写一个Python脚本并运行它。这样的脚本可能看起来像

import nltk
import sklearn

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.

请注意,并非所有Python软件包都保证具有__version__属性,因此对于某些其他软件包可能会失败,但是对于nltk和scikit-learn至少它会起作用。

import nltk is Python syntax, and as such won’t work in a shell script.

To test the version of nltk and scikit_learn, you can write a Python script and run it. Such a script may look like

import nltk
import sklearn

print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))

# The nltk version is 3.0.0.
# The scikit-learn version is 0.15.2.

Note that not all Python packages are guaranteed to have a __version__ attribute, so for some others it may fail, but for nltk and scikit-learn at least it will work.


回答 1

试试这个:

$ python -c "import nltk; print nltk.__version__"

Try this:

$ python -c "import nltk; print nltk.__version__"

回答 2

在Windows®系统中,您可以尝试

pip3 list | findstr scikit

scikit-learn                  0.22.1

如果您在Anaconda上,请尝试

conda list scikit

scikit-learn              0.22.1           py37h6288b17_0

这可以用来找出您已安装的任何软件包的版本。例如

pip3 list | findstr numpy

numpy                         1.17.4
numpydoc                      0.9.2

或者,如果您想一次查找多个包裹

pip3 list | findstr "scikit numpy"

numpy                         1.17.4
numpydoc                      0.9.2
scikit-learn                  0.22.1

请注意,当搜索多个单词时,必须使用引号字符。

照顾自己。

In Windows® systems you can simply try

pip3 list | findstr scikit

scikit-learn                  0.22.1

If you are on Anaconda try

conda list scikit

scikit-learn              0.22.1           py37h6288b17_0

And this can be used to find out the version of any package you have installed. For example

pip3 list | findstr numpy

numpy                         1.17.4
numpydoc                      0.9.2

Or if you want to look for more than one package at a time

pip3 list | findstr "scikit numpy"

numpy                         1.17.4
numpydoc                      0.9.2
scikit-learn                  0.22.1

Note the quote characters are required when searching for more than one word.

Take care.


回答 3

要检查shell脚本中scikit-learn的版本,如果已安装pip,则可以尝试以下命令

pip freeze | grep scikit-learn
scikit-learn==0.17.1

希望能帮助到你!

For checking the version of scikit-learn in shell script, if you have pip installed, you can try this command

pip freeze | grep scikit-learn
scikit-learn==0.17.1

Hope it helps!


回答 4

您只需执行以下操作即可找到NLTK版本:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

对于scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

我在这里使用python3。

You can find NLTK version simply by doing:

In [1]: import nltk

In [2]: nltk.__version__
Out[2]: '3.2.5'

And similarly for scikit-learn,

In [3]: import sklearn

In [4]: sklearn.__version__
Out[4]: '0.19.0'

I’m using python3 here.


回答 5

您可以按照以下方式从python笔记本单元格中进行检查

!pip install --upgrade nltk     # needed if nltk is not already installed
import nltk      
print('The nltk version is {}.'.format(nltk.__version__))
print('The nltk version is '+ str(nltk.__version__))

#!pip install --upgrade sklearn      # needed if sklearn is not already installed
import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print('The scikit-learn version is '+ str(nltk.__version__))

you may check from a python notebook cell as follows

!pip install --upgrade nltk     # needed if nltk is not already installed
import nltk      
print('The nltk version is {}.'.format(nltk.__version__))
print('The nltk version is '+ str(nltk.__version__))

and

#!pip install --upgrade sklearn      # needed if sklearn is not already installed
import sklearn
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print('The scikit-learn version is '+ str(nltk.__version__))

回答 6

在我的安装了python 2.7的ubuntu 14.04机器中,如果我去这里,

/usr/local/lib/python2.7/dist-packages/nltk/

有一个名为

VERSION

如果我这样做,cat VERSION它将打印3.1,这是已安装的NLTK版本。

In my machine which is ubuntu 14.04 with python 2.7 installed, if I go here,

/usr/local/lib/python2.7/dist-packages/nltk/

there is a file called

VERSION.

If I do a cat VERSION it prints 3.1, which is the NLTK version installed.


Shell脚本:从Shell脚本中执行python程序

问题:Shell脚本:从Shell脚本中执行python程序

我尝试谷歌搜索答案,但没有运气。

我需要使用我的超级计算机服务器,但是要运行我的python脚本,必须通过shell脚本执行。

例如我要job.sh执行python_script.py

如何做到这一点?

I’ve tried googling the answer but with no luck.

I need to use my works supercomputer server, but for my python script to run, it must be executed via a shell script.

For example I want job.sh to execute python_script.py

How can this be accomplished?


回答 0

只要确保python可执行文件在PATH环境变量中,然后在脚本中添加

python path/to/the/python_script.py

细节:

  • 在文件job.sh中,放入
#!/bin/sh
python python_script.py
  • 执行以下命令以使脚本可运行: chmod u+x job.sh
  • 运行 : ./job.sh

Just make sure the python executable is in your PATH environment variable then add in your script

python path/to/the/python_script.py

Details:

  • In the file job.sh, put this
#!/bin/sh
python python_script.py
  • Execute this command to make the script runnable for you : chmod u+x job.sh
  • Run it : ./job.sh

回答 1

方法1-创建一个shell脚本:

假设您有一个python文件,请hello.py 创建一个名为的文件job.sh,其中包含

#!/bin/bash
python hello.py

将其标记为可执行

$ chmod +x job.sh

然后运行它

$ ./job.sh

方法2(更好)-使python本身从shell运行:

修改脚本hello.py并将其添加为第一行

#!/usr/bin/env python

将其标记为可执行

$ chmod +x hello.py

然后运行它

$ ./hello.py

Method 1 – Create a shell script:

Suppose you have a python file hello.py Create a file called job.sh that contains

#!/bin/bash
python hello.py

mark it executable using

$ chmod +x job.sh

then run it

$ ./job.sh

Method 2 (BETTER) – Make the python itself run from shell:

Modify your script hello.py and add this as the first line

#!/usr/bin/env python

mark it executable using

$ chmod +x hello.py

then run it

$ ./hello.py

回答 2

恕我直言

python /path/to/script.py

是非常错误的,尤其是在这些日子里。哪个Python?python2.6?2.7?3.0?3.1?大多数时候,您需要在python文件的shebang标记中指定python版本。我鼓励使用

#!/ usr / bin / env python2 #or python2.6或python3甚至python3.1
为了兼容性。

在这种情况下,使脚本可执行并直接调用它会更好:

#!/ bin / bash

/path/to/script.py

这样,您所需的python版本就只写在一个文件中。如今,大多数系统同时具有python2和python3,并且碰巧symlink python指向python3,而大多数人希望它指向python2

Imho, writing

python /path/to/script.py

Is quite wrong, especially in these days. Which python? python2.6? 2.7? 3.0? 3.1? Most of times you need to specify the python version in shebang tag of python file. I encourage to use

#!/usr/bin/env python2 #or python2.6 or python3 or even python3.1
for compatibility.

In such case, is much better to have the script executable and invoke it directly:

#!/bin/bash

/path/to/script.py

This way the version of python you need is only written in one file. Most of system these days are having python2 and python3 in the meantime, and it happens that the symlink python points to python3, while most people expect it pointing to python2.


回答 3

将以下程序另存为print.py

#!/usr/bin/python3
print('Hello World')

然后在终端中输入:

chmod +x print.py
./print.py

Save the following program as print.py:

#!/usr/bin/python3
print('Hello World')

Then in the terminal type:

chmod +x print.py
./print.py

回答 4

这最适合我:在脚本顶部添加以下内容:

#!c:/Python27/python.exe

(C:\ Python27 \ python.exe是我机器上python.exe的路径),然后通过以下命令运行脚本:

chmod +x script-name.py && script-name.py

This works best for me: Add this at the top of the script:

#!c:/Python27/python.exe

(C:\Python27\python.exe is the path to the python.exe on my machine) Then run the script via:

chmod +x script-name.py && script-name.py

回答 5

这对我有用:

  1. 创建一个新的外壳文件作业。这么说吧: touch job.sh并添加命令以运行python脚本(您甚至可以向该python添加命令行参数,我通常会预先定义命令行参数)。

    chmod +x job.sh

  2. 在内部job.sh添加以下py文件,例如:

    python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"

    python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"

job.sh的输出应如下所示:

Done with python_file.py

Done with python_file1.py

通常,当我必须运行带有不同预定义参数的多个python文件时,通常会使用它。

注意:快速了解此处发生的情况:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 

  • 在这里,shell脚本将运行python_file.py文件,并在运行时将多个命令行参数添加到python文件。
  • 这不一定意味着,您也必须传递命令行参数。
  • 您可以像这样python python_file.py简单,简单地使用它。接下来,>>将打印此.py文件的输出并将其存储在testpy-output.txt文件中。
  • &&是一个逻辑运算符,仅在成功执行以上操作后才运行,并且作为可选回显 “用python_file.py完成”将在运行时回显到cli / terminal上。

This works for me:

  1. Create a new shell file job. So let’s say: touch job.sh and add command to run python script (you can even add command line arguments to that python, I usually predefine my command line arguments).

    chmod +x job.sh

  2. Inside job.sh add the following py files, let’s say:

    python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file.py"

    python_file1.py argument1 argument2 argument3 >> testpy-output.txt && echo "Done with python_file1.py"

Output of job.sh should look like this:

Done with python_file.py

Done with python_file1.py

I use this usually when I have to run multiple python files with different arguments, pre defined.

Note: Just a quick heads up on what’s going on here:

python_file.py argument1 argument2 argument3 >> testpy-output.txt && echo "completed with python_file.py" . 

  • Here shell script will run the file python_file.py and add multiple command-line arguments at run time to the python file.
  • This does not necessarily means, you have to pass command line arguments as well.
  • You can just use it like: python python_file.py, plain and simple. Next up, the >> will print and store the output of this .py file in the testpy-output.txt file.
  • && is a logical operator that will run only after the above is executed successfully and as an optional echo “completed with python_file.py” will be echoed on to your cli/terminal at run time.

回答 6

您应该能够像python scriptname.py例如调用它

# !/bin/bash

python /home/user/scriptname.py 

另外,请确保脚本具有运行权限。

您可以使用来使其可执行chmod u+x scriptname.py

You should be able to invoke it as python scriptname.py e.g.

# !/bin/bash

python /home/user/scriptname.py 

Also make sure the script has permissions to run.

You can make it executable by using chmod u+x scriptname.py.


回答 7

我用这个并且很好用

#/bin/bash
/usr/bin/python python python_script.py

I use this and it works fine

#/bin/bash
/usr/bin/python python python_script.py

回答 8

由于其他帖子都说了所有(我在寻找以下内容时偶然发现了该帖子)。
这是从另一个python脚本执行python脚本的方法:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

您可以通过提供其他一些参数来提供args sys.argv

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv