I've recently heard that you can change the prompt in python by changing variable sys.ps1. So I've decided to open IDLE, and write something like that:
>>> import sys
>>> sys.ps1 = ":::"
However, that created a new variable and nothing changed (prompt was still ">>>") - I rebooted IDLE and checked is this variable read by python... Nope:
>>> sys.ps1
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
sys.ps1
AttributeError: module 'sys' has no attribute 'ps1'
So, how do I change the prompt in python?
NOTE: The other functions/variables of sys module were read properly.
See issue #13657, "IDLE doesn't recognize resetting sys.ps1", on the Python bug tracker. It was opened in 2011 and is still unresolved (as of this writing). So it is not possible to change the prompt from within IDLE's Python shell simply because IDLE does not support that.
Update (less than 24 hours later): The issue is now closed. In the upcoming version of IDLE, to be released with Python 3.10, prompts will be displayed differently. See comment by IDLE developer Terry Jan Reedy above. A setting to change the prompt may be added in the future.
In the current and earlier Python/IDLE releases, the prompt can be customized before starting IDLE, but not while running it. You'd need a little start-up script that does this:
import sys
sys.ps1 = '::: '
import idlelib.idle
The reason you get that error message (module 'sys' has no attribute 'ps1') is because the Python shell that IDLE presents to you is not actually in "interactive" mode. And only then is sys.ps1 defined. You'd see the same error message if you tried to access sys.ps1 in any other Python program that is directly executed. In this case, that Python program is IDLE itself.
The prompt strings specifying the primary and secondary prompt (their initial values in this case are >>> and ... ) of the interpreter are only defined if the interpreter is in interactive mode and IDLE is more or less an integrated development environment for Python
Python interactive mode:
sys.ps1 doc
Related
I use Python without a GUI/IDE by issuing Python from the Bash command line. I use it within a Cygwin environment, which behaves like a Linux system in many respects.
The file used for the history of commands issued at the Python command line is stored in ~/.python_history. I can easily scoot in and yank content for manipulation using vim's Buffer Explorer. It's also easy to yank manipulated content into the system clipboard for pasting at the Python command line. (For more tactical revisions of commands, on the other hand, I just use readline to vim previous commands and a single-line basis.)
I have found that ~/.python_history doesn't update after each command. I'm not sure how often it is updated, but it's clear that exiting Python causes it to update. Putting into the background with Ctrl+Z does not.
(Is there a quick and convenient way from the Python command line to force an update to ~/.python_history?
Since my original posting of this question, I've had occasion to figure out Linux (Ubuntu) as a VirtualBox virtual machine. However, it seems very excessive to fire up an entire guest operating system just to be able to access the command history as a palette as opposed to one line at a time using the Up-Arrow key (or equivalently, k if one's command line editor is set to Vim). I'd even be happy with a Python counterpart to Bash's "fix command" (fc) command, even though I would have to erase all the lines that I don't want to execute.
Various things tried
As per the responses, I tried importing readline.write_history_file, but it isn't recognized, even though readline itself is:
$python
Python 3.8.10 (default, May 20 2021, 11:41:59)
[GCC 10.2.0] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
# Show modules
>>> import sys
>>> modulenames = set(sys.modules) & set(globals())
>>> allmodules = [sys.modules[name] for name in modulenames]
>>> print(allmodules)
[<module 'sys' (built-in)>]
# Fail to import readline.write_history_file
>>> import readline.write_history_file as whf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'readline.write_history_file'; 'readline' is not a package
# However, readline itself imports
>>> import readline
>>> readline.get_history_item(2)
'version'
readline does appear to be explicitly part of the Cygwin repository, so I didn't try pip install readline:
Search Cygwin packages for readline (followed by browser search for the string python)
The one result that appears to be most relevant shows dll,py, and pyc files with readline[s] in the file name, but I'm not sure what that says about the form taken by the readline module itself. I welcome clarifications/explanations about this.
In fact, I'm reluctant to try installing anything outside of the Cygwin package manager using pip for fear of creating inconsistencies.
Reading through this module, I found out readline.write_history_file(path) may be what you are searching for:
Save the history list to a readline history file, overwriting any existing file.
The default filename is ~/.history
First thing in the interactive interpreter, do
import readline.write_history_file as whf # write history file
Then you can do whf() or whf("path/to/.historyfile"), and your python history gets saved to disk immediately.
EDIT:
I'm not sure how often it is updated
It is only updated when you exit the interpreter. If you kill it, the history won't get saved, and Ctrl+Z just causes the interpreter to be suspended. If you then unsuspend it (by executing fg or bg, for example) and exit it normally, the history file will get written.
I am fairly new to programming in python. I installed anaconda and am running iPython (the Jupyter qtconsole) v.4.3.0 and python v.3.6 on a Mac. Currently, I am trying to import a module with functions located in my home directory.
I have looked at stackoverflow and python documentation and found that it could be done with:
%run "Users/myUser/python_functions.py"
or
import python_functions
However, when I try both of these approaches, I get prompted to overwrite the file that I am running or importing:
File `python_functions.py` exists. Overwrite (y/[N])?
This is changing the previous file and not getting the functions I want to be imported.
What may explain this, and what can I do to import my module?
this is wrong but leaving it up for shame
import on ubuntu (and I'm guessing many other unix-like OSs including Mac) is a utility that saves any visible window on an X server and outputs it as an image file. You can capture a single window, the entire screen, or any rectangular portion of the screen.
My guess if you are running the import command in your console, and it's about to take a screenshot and save it over an existing file - python_functions
Before you the use the python import command, start a python interpreter:
$ python
>>>import yourfile
edit: on re-reading your question, I'm not so sure about my guess anymore, but leaving it up until you tell me I'm wrong :)
Running Jupyter qtconsole as an interpreter is likely causing the problem in this scenario. Instead using a IDE or command line interpreter will resolve it .
Since anaconda was installed, trying it with the IDE Spyder executes the code just fine without the overwrite prompt. It works on others (e.g PyCharm, Rodeo, etc.) as well.
I am trying to configure PyCharm: I need to write my script in the main editing window and then I want to check in the Python console window whether the results (variables, lists) work as expected.
Nonetheless, as I start using the Python console after running the script, the console has not collected any data from the running process.
The "Python Console" is a separate environment from the one you run code in when you press "Run...".
First of all: Use the excellent debugging facilities provided by PyCharm to step through your code and see whether things work as they should in situ.
If that for some reason doesn't do it for you:
You can from <yourfile> import * in the console, if running pure python. That will get you your variables. If you do import <yourfile>, the script will be run, but your variables will only be available as <yourfile>.<var>. Of course, anything you have under if __name__ == '__main__' won't be executed.
If this won't do, I refer you to https://stackoverflow.com/a/437857/3745323:
with open("yourfile.py") as f:
code = compile(f.read(), "yourfile.py", 'exec')
exec(code, global_vars, local_vars)
You can definen that as a function in a separate file and import it. Alternatively, just type it into the interpreter.
If you have IPython installed, recent PyCharm editions default to using it in the console. In this case you can use the %run magic to run your script as if it was typed in line-by-line into the interpreter.
In[2]: %run yourfile
The example shows:
I create a simple module (fibonacci calculator)
I start a pycharm console, import the module, run the function inside console, and it works.
Now I edit some print text in the module.
Go back to the console and run "import fibagain"
The console seems to do this without complaining.
But when I run the fib() function, it is still giving me results from the earlier version. I cannot make the console see the updated version of the fibagain.py file.
If I delete the console and open it again, then 'import fibagain', running fib(3) will give me the latest version.
sorry, but not permitted to post proper image links here. This address shows the screencapture:
Instead of import again, you want:
reload(fibagain)
This will reload the updated module. (Note: This only works if fibagain had been imported some time earlier)
I am having trouble getting PYTHONPATH set. I have added this line to ~/.bashrc
export PYTHONPATH=$PYTHONPATH:/home/sayth/My_Programs/Python
I ran source ~/.bashrc
Here is the issue though if I type python at the terminal and get a python REPL I can then import modules from ~/My_Programs/Python without a problem.
However if I run bpython or idle or a console in ninja-ide etc then import fails.
>>> import temperature
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import temperature
ImportError: No module named temperature
>>>
I can do sys.path.append(/home/sayth/My_Programs/Python) and get it working, but I wanted the PYTHONPATH to work in all consoles automatically. How?
PS using ubuntu 11.10
I'm going to guess that you did not launch your ninja-ide from the same terminal that you source ~/.bashrc from -- the new environment variable only influences child processes of whichever shell process did the sourcing. Of course, logging out and in again may do it, but if you're living entirely in the GUI (e.g., you click a button to start the ninja-ide), then you may need to go to some more effort to set your environment variable. How you do so depends upon which graphical environment you're using.