How to Pre-load Python Modules in Python IDLE on Startup? - python

I am on Windows 7. When I launch Python IDLE, I want it to pre-load: pandas, numpy and matplotlib without me having to type out the import statements. I import them very frequently.
I have waded through several posts:
This one has to do with iPython, not IDLE-specific
This one has to do with running a script in IDLE
This one talks about PYTHONSTARTUP for interactive sessions
From these posts, I have determined that there is a distinct difference between Windows command-prompt python interactive shell and IDLE's interactive shell.
For example, I created defaultimports.py and put it in this location:
C:\Python34\Lib\site-packages\jaradspythonstartup
That script contains the following:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
print('pd, np and plt imported')
Next, on my machine, I went to Start > Computer > right-clicked Properties > Advanced system settings > environment variables > clicked New... and added a new variable named PYTHONSTARTUP, then put my path C:\Python34\Lib\site-packages\jaradspythonstartup\defaultimports.py
However, this seems to only work in Windows Command prompt when I open command prompt and type python. I do see it loads my print statement.
When I launch IDLE, I don't see the message: pd, np, and plt imported print statement. While in IDLE, if I import os and os.environ['PYTHONSTARTUP'], I do see my environment variable defined but don't know if that's important to note or not.
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import os
>>> os.environ['PYTHONSTARTUP']
'C:\\Python34\\Lib\\site-packages\\jaradspythonstartup\\defaultimports.py'
>>>
My Question
How can I pre-load modules in IDLE on startup?

python -m idlelib -h on a command line, where python runs recent 3.x, will display startup commands for IDLE; use idlelib.idle for 2.x. It says that
idle idlelib -s "runs $IDLESTARTUP or $PYTHONSTARTUP before anything else".
If that does not work, try python -m idlelib -s.
Currently, when you restart the shell, which happens when you run a file from the editor, ....STARTUP does not get re-run. I hope to fix that.
EDIT: How to start IDLE with arguments from the desktop instead of command line.
Make a properly labelled IDLE desktop icon. Go to Start Menu > Python x.y > IDLE... and copy to Desktop. Control-Left Mouse Button drag or (Win 7, at least) Right click, Send to > Desktop (create shortcut). If for Python before 3.4, right click icon, select Rename, and label with the version number. (We recently got complaint "I installed 3.5 and (pre-existing) desktop icon opens 2.7.).
Make icon open IDLE with arguments. Right-click icon, select properties, click end (you may or may not have to click box first). Cursor should be at end of line with ...pythonw.exe...idlew.py. Space and add arguments. I tried -c "print('hello')" to test. Add -s for ...STARTUP. Consider renaming to indicate addition, such as IDLE 3.5 64 bit STARTUP, in case you want another IDLE desktop icon.

Related

Spyder IDE with python 3.10 seems freezing when click run button, but it works fine if run a single line beforehand running the entire script

I have truble with last version of Spyder 5.4.0 with last version of Python 3.10.6.
Spyder version: 5.4.0 (conda)
Python version: 3.10.6 64-bit
Qt version: 5.15.2
PyQt5 version: 5.15.7
Operating System: Windows 10
Even if running a script like
print('Hello world')
when I click on the play green button, the IPython console seems freezing on this script, and it does not run for hours.
If I select this line of code and I run current selection or run the current cell it works fine. From this moment, it seems that spyder works fine, until at a certain point when I run it seems again freezing. I have to restart a new console and before running the script I have to run a single line or a single cell.
It seems that I have to 'activate' in someway the Python console in order to Spyder will run the script.
Does anyone have the same issue? How can I solve it?
I have tried to uninstall and reinstall both spyder and python many times, but it is useless.
After many trials, I noticed that there is something strange with IPython console. I noticed that when it hangs after running a code, if I delete all user variables, it worked fine.
Then I tryed to delete all variables before execution, and it work fine.
Therefore I discovered that a solution that worked for me is to go to preferences -> Run -> and untick the option 'Remove all variables before execution'
It is quite annoying because I have to do it manually every time before running, but in this way the spyder does not appear to hang anymore! I hope that the Spyder developers will solve it soon.
-
I automatically solved by typing at the beginning of any script these lines, inspired from the question Code to clear console and variables in Spyder :
try:
from IPython import get_ipython
get_ipython().magic('clear')
get_ipython().magic('reset -f')
import matplotlib.pyplot as plt
plt.close('all')
except:
pass
similar to Matlab in which you normally start your code with
clc
close all
clear all

Force Python to update command history file from command line?

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.

Not able to import my created module in python

Python is very first programming language i'm learning , i'm following "python programming by John Zelle". The problem is that after creating module Chaos i'm not able to import this module, it shows error message that " Import error: No module name chaos.
I can see the confusion. I have actually read this book as well when I was learning. First be sure you launch python in the same directory as Chaos.py and be sure to use a capital C if that is how you named it.
To import it in the python interpreter you would not type import Chaos.py just import Chaos and then call the main function as follows:
import Chaos
Chaos.main()
If you wanted to run the script in python you can just type the following from a command line in the same directory as the .py file:
python chaos.py
(These directions assume Python 3 on Windows. If your system is different then please edit the question to tell your system and version.) First create a file named chaos.py on your desktop. In the file, paste the following:
# File: chaos.py
def main():
print("This program illustrates a chaotic function")
x = float(input("Enter a number between 0 and 1:"))
for i in range(10):
x = 3.9*x*(1-x)
print(x)
if __name__ == "__main__":
main()
Next, to make this as easy as possible, we will use a modified IDLE shortcut:
Copy your current IDLE shortcut and paste it to your desktop to create a new shortcut.
Right-click on the new shortcut and click Properties.
Change the Start In box to %USERPROFILE%\Desktop. Click OK.
Now open IDLE by clicking on the new shortcut. Then enter:
import chaos
chaos.main()
There's an easy solution, the way I got it to work was instead of making the module perform inside a IDLE environment, I opened up sublime text(a program similar to notepad++), and I essentially wrote the code inside of there and saved it as a python file called "Chaos.py" inside of the folder where IDLE runs, which is :
(C:\Users\ngltm\AppData\Local\Programs\Python\Python36-32\) )
, the name next after the "Users" will be different for you, but I saved it inside of the Python36-32 file and after saving it inside of sublime text, I opened up a IDLE program and wrote "import Chaos" and it worked! The problem was the text in the beginning of every IDLE file that starts off with :
"Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 16:07:46) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information."
Well, I hope this helped!

PyDev Interactive Python Shell in Eclipse

I've been using Wing IDE for python programming and I am trying to switch to Eclipse, PyDev.
When I run my code in Wing IDE, after finishing the execution the console goes right back to the interactive shell and I can continue on testing, but I don't know how to do this in Eclipse.
I'm not sure if I am describing my problem properly so I'll use an example:
Let's say I had a simple source code that looked like this (e.g. test.py):
print("hello")
When I run this in Wing IDE by clicking that green arrow, the console would look like this after execution:
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "help", "copyright", "credits" or "license" for more information.
[evaluate untitled-1.py]
hello
>>>>
And I can keep doing whatever on the shell and it would know my code (defined functions etc.).
But when I do the same thing in Eclipse, the console would simply look like this:
hello
and I have to click "Remove All Terminated Launches" button to go back to the shell.
Can this be done in Eclipse?
What you want to use is the interactive console in PyDev (not the regular output when you do a run).
To use it do: Ctrl+Alt+Enter.
Note that if you're in the middle of a debug session, you can also use the debug session console to interact with the program.
It can also be created from the UI in the console view as shown below:
[
From what I know, we can open multiple consoles of a particular type in Eclipse.
Whenever we run a script within PyDev, it opens a new console to which it prints the output from the script (including error output). However this is just a new console that is added to the list of already opened consoles. Hence you can switch back to a previously open console by using the Display Selected Console option within the console view ( refer here for a list of all the available console options).
What does this mean?
You can open a new Python interpretor console using the Open Console option within the Eclipse Console view. You can define your methods and play with the interpretor within that console. You now run a Python script that is open within the PyDev editor. A new console gets opened up where-in you see the output from the script (includes error output too). Now if you want to go back to the interactive console, you simply choose the Python Interepretor console that you opened previously from the Display Console option.
Personally, I like this design where-in the output from your script does not mingle and mess up with your experimental sojourns on the Python console. This in turn results in a crisp, clear and concise view of what is happening within the various python environments.
Hope this bit of information helps.

How to start Python IDLE from python.exe window if possible, and if not, what is python.exe even used for?

I am running Windows 7 currently, and I remember when using Linux at the school computers I was able to type "gedit &" into the terminal for example to open up the gedit text editor. I was wondering whether there is a similar process to open IDLE, and for that matter a Python program/script by typing it into the "terminal-equivalent." I'm a complete newbie, so I may be off-base a bit...anyways, so there is this terminal-like program called python.exe, and it seems like it should be able to open Python-related software (like IDLE), and I was wondering 1) what python.exe is for, 2) whether it can be treated like a Linux terminal, and 3) how to do stuff in it. I've tried various commands and I get a syntax error for virtually everything. Much appreciated!
python.exe is the Python interpreter. All of your Python programs are executed with it. If you run it in the console, you will get an interactive prompt:
C:\> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
If you give it a Python program, it will run it:
C:\> python myprog.py
You can also ask it to run an importable module:
C:\> python -m modulename
You can run IDLE this way:
C:\> python -m idlelib.idle
Yes you can start libraries like Idle, you need to import idlelib:
import idlelib.idle
Alternatively, to start idle from terminal without getting into python.exe shell first, you can do python.exe -m idlelib.idle assuming that idlelib is in your PYTHONPATH
The python.exe, is just like the shell in IDLE, is mainly used for quick experimentation with algorithms you want to try or testing library calls or language features, when you don't want to open a new file for that purpose. There are similarities with Linux shells like bash, but python's shell are heavily oriented for aiding programming while Linux shell are heavily oriented for starting up other programs. While you can start other programs in python's shell using subprocess.Popen and while bash do have it's own scripting language, they are very different.
python.exe is Python, the python interpreter specifically.

Categories

Resources