(ve)[kakarukeys@localhost ve]$ python
Python2.6.6(r266:84292,Nov152010,21:48:32)[GCC 4.4.420100630(RedHat4.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;5AFile"<stdin>", line 1[1;5A^SyntaxError: invalid syntax
>>>^[p
File"<stdin>", line 1
p
^SyntaxError: invalid syntax
>>>
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)Returnwhile 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.
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:
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.
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. :)
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.
对于OSX,您不需要像pyfunc的答案这样的自定义脚本(至少在特立独行的情况下)。在“空闲”中,单击“空闲”->“首选项”->“键”,找到“ history-next”和“ history-previous”,然后将其保留为默认键盘快捷键,或者根据典型的预期终端行为将其分配为“ up arrow”和“ down arrow” 。
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.
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.
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
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.
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.
Python2.5.1(r251:54863,Apr152008,22:57:26)[GCC 4.0.1(AppleInc. build 5465)] on darwin
Type"help","copyright","credits"or"license"for more information.(InteractiveConsole)
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?
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.
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
Python2.7.5(default,Jun112019,14:33:56)[GCC 4.8.520150623(RedHat4.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
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:
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).
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.
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.
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)
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.
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.
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.
“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.
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 <).
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.
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.
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.
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!
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.
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.
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.
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?
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
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:
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.
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
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.
#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
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.
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.
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.
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 PATHbefore editing:
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.
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.
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.
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:
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.
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.
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.
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’
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:
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:
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.
>>>import hashlib>>> h = hashlib.md5()>>> h.update("mystringforhash")>>>print h.hexdigest()86b6423cb6d211734fc7d81bbc5e11d3# Result from Python
$ echo mystringforhash | md5sum686687dd68c5de717b34569dbfb8d3c3-# 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
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:
import subprocess
subprocess.call(['python','helloworld.py'])# Just run the program
subprocess.check_output(['python','helloworld.py'])# Also gets you the stdout
import subprocess
subprocess.call(['python', 'helloworld.py']) # Just run the program
subprocess.check_output(['python', 'helloworld.py']) # Also gets you the stdout
空闲外壳窗口与终端外壳(例如,运行sh或bash)不同。而是就像在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])
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)
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:
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
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.
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.
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 installedimport 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 installedimport 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__))
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.
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
Inside job.sh add the following py files, let’s say:
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.
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