Run a module in IDLE (Python 3.4) without Restart - python

It appears that, in the past, IDLE did not restart (clean the environment) when you ran a script (module). Today, however, this is the case. But for prototyping I would like the environment (assigned variables, imported modules, functions, ...) to survive running different modules (files).
Example: I am working on a function, let's call it f7(), that requires a certain environment. The environment is built in another script (file), say, env1.py. After env1.py has been run, I can built on all imported modules, defined functions and assigned variables, when working at the command line of IDLE. But I cannot run another file, where my f7() resides! I would have to redefine f7() at the interpreter's command line. Which I of course do not do, because f7() is very lengthy. The only thing that remains is to include f7() in env1.py. And restart it after every change to f7(). As a consequence, I have to wait each time until env1.py has finished. Which is a waste of time, because every time it runs, it does the same. I only change f7()...
Can I tell IDLE not to restart (clean environment) each time I run a module (file) in IDLE? If not, what alternatives to IDLE are capable of something like this??
It seems IDLE behaves the same on Windows, Ubuntu, Raspbian. I am using Python 3.X on each of these systems.

I am not aware that IDLE ever didn't restart when running a editor file, so that would have to have been several years ago. I will think about it as a new feature though.
EDIT: Added in June 2019: On the editor Run menu, Run... Customized opens a dialog with [X] Restart. Uncheck that box and the restart is skipped.
END EDIT
In the meanwhile, you can do this for the specific scenario you gave. Load env1.py into an editor window and run it. When >>> appears, enter or paste the def statement for f7 and run it. (Paste after loading the file with f7 and copy.) Test by calling f7. To edit the definition of f7, recall it to the current >>> line. Either click on the previous definition and hit Enter or use the history keyboard shortcuts (for me on Windows, Alt-P for Previous, Alt-N for Next). In either case, edit and re-run. Do the same with test statements. I recall and edit statements routinely.

Related

Changes in the module are not importing to the run file (unless PyCharm is restarted)

I have created a module of functions in the form of a separate module.py file. I make updates to the functions in the module as I develop my code. However, when I go back to the run file (main) to call the updated functions, the updates have not been picked up (i.e., the run file calls the old version of the function), and often aren't picked up unless I re-start PyCharm.
I have tried:
Saving the module.py file, then reimporting it in the run file before calling functions from it
Clearing the console using Rerun (green curved arrow in console) before re-running the script
Adding a 'reload(module)' statement in before the function call in the run file
(For the avoidance of doubt, the import statement for the module is in the run file and works the first time I call it. It just doesn't efficiently pull through updates when I reimport it).
Note: JetBrains support have since suggested the following as a solution.
"First of all, if you're using version 2020.1, I suggest updating to 2020.2, and then check File | Settings | Appearance & Behavior | System Settings | Autosave settings to make sure the changes are saved. If this doesn't help and the issue is still reproduced in PyCharm, please try running your code from the terminal outside of IDE, and check if the behavior is the same."
I can't update to the new version yet to test it (some of my critical plugins are incompatible), but this may be useful for others. In the meantime, clearing the console in between each run using Rerun (curved green arrow) seems to be working now.

Pydev Django project compilation

I installed pydev and eclipse to compile a django project. Everything looks good but one thing makes me crazy. When i change something in the code, i click to save it and hope to see the effect of changes. However, I cannot see the effect of what i change unless I terminate the program and re-run as as shown below. It is such a pain...
I used to use Pycharm, but it expired. In Pycharm, when the program runs once, i do not need to run it again and again. I can easily see the effect of my changes on the code by clicking save button. Is it possible to see the same thing in pydev and eclipse? Do you guys also see this issue?
To debug Django with the autoreload feature, the Remote Debugger must be used and a patch must be applied to your code (just before the if _name_ == "_main_": in your manage.py module):
import pydevd
pydevd.patch_django_autoreload(
patch_remote_debugger=True, #Connect to the remote debugger.
patch_show_console=True
)
So, doing that, starting the remote debugger and making a regular run should enable all the regular breakpoints that are put inside Eclipse to work in the Django process with the Remote Debugger (and the --noreload that PyDev added automatically to the launch configuration must be removed).
I have plans on improving that so that the debugger will automatically add tracing to spawned processes (probably for the next release), but on PyDev 3.3.3 this still requires doing this manual patch and using the remote debugger.
The above is related to a debug run. Now, on to the regular run...
When you do a run as > pydev: django, it should create a run configuration (which you can access at run > run configuration). Then, open that run configuration > arguments and remove the '--noreload' (leaving only the 'runserver' argument).
Then, you can simply rerun it with Ctrl+F11 (if you've set it to launch the previously launched application as indicated in http://pydev.org/manual_101_run.html)
-- (Or alternatively you can run it with: Alt + R, T, 1).
The only problem is that if you kill the process inside Eclipse it's possible that it leaves zombie processes around, so, you can use the pydevd.patch_django_autoreload(patch_show_console=True) as indicated above to open a console each time it spawns a new process (you can do a pydevd|<- ctrl space here to add an import to pydevd).
Note that this should work. If it's not working, make sure you don't have zombie processes around from a previous session (in windows you can do: taskkill /F /IM python.exe to make sure all Python processes are killed).
Another note (for when you don't actually have automatic reload): Ctrl+Shift+F9 will kill the currently running process and re-run it.

Linux desktop file Exec doesn't used the user session

I have a python script file that works perfectly when I use it from the terminal.
Now I have created the following .desktop file in order to launch it easily:
[Desktop Entry]
Name=Test
GenericName=Test
Comment=My test script
Type=Application
Exec=/opt/test.py
Icon=/opt/test.png
Categories=Utils;
When I launch it the GTK window appear but clicking a button that call an init.d script make it working not properly.
Therefore adding Terminal=true make it working perfectly but I don't want to have that terminal open.
So I have then put the following code in order to log the environment variables:
import os
with open("/tmp/py_env.log", "w") as env_log:
env_log.write(str(os.environ))
and found differences.
So my question is how to write the .desktop file so that my application is running like if I start it from my terminal (without having an opened terminal :))
The problem is valid, but I think "replicating the terminal environment" is the wrong approach to solve it.
Indeed, what makes the application work is not the fact that it's launched from the terminal, it's that the terminal happens to have some environment variables which matter to your application.
Therefore, what you should aim for is to have those environment variables set properly at all times, rather than assuming the terminal environment will always happen to contain them all the time for all your users.
Thus, you should:
Check which environment variables are different between the two environments
Make a list of those which matter (i.e. those which would make the .desktop file work properly), and of what their value needs to be for the script to work
Either:
Create a wrapper script for your Python script, which initializes those environment variables properly, OR
Set those environment variables from inside the Python script itself.
this question is similar to .bashrc not read when shell script is invoked from desktop shortcut
either initialize your environment in ~/.bash_profile instead of
~/.bashrc
OR
make your *.desktop file call a wrapper that initializes your
environment - e.g. by sourcing ~/.bashrc (or whatever script is
responsible now).
the second solution is more specific (does not effect all other unrelated launches of your shell) in should thus be preferred.
Thanks anyone to have participate to this question.
I have solved this issue by implemented use of pkexec instead of gksudo.
pkexec seems to reuse the current user environment then I don't have this issue anymore.
Thanks.

Running a module from the pycharm console

I'm new to python and pycharm and I'd like to run a module from the pycharm console in the same way as you can from IDLE, if it's possible.
The idea is to create simple functions and test them "live" using the console.
...how do you do that in pycharm?
Running python scripts using pycharm is pretty straightforward, quote from docs:
To run a script with a temporary run/debug configuration Open the
desired script in the editor, or select it in the Project tool window.
Choose Run on the context menu, or press Ctrl+Shift+F10. So
doing, a temporary run/debug configuration is created on-the-fly.
Besides there is a "Python Console" available in pycharm: see documentation.
UPD:
Here's an example.
Imagine you have a python module called test_module.py:
def a(*args, **kwargs):
print "I'm function a"
def b(*args, **kwargs):
print "I'm function b"
Then, in pycharm's "Python Console" you can do this:
>>> from test_module import *
>>> a()
I'm function a
>>> b()
I'm function b
If you need to execute a part of an existing code, you can use the Execute Selection in Console feature: select the code snippet -> right click -> "Execute Selection in Console".
For anyone still having this problem: Go to the Run/Debug menu, choose Edit Configuration, check the box 'Show command line' this will enable you to enter parameters in the console at the >>> prompt and test your function.
Edit: To make this change apply to all your .py files (as this check box only applies to the current file you're working on) go to: Edit configuration, in the pop up you will see a menu tree on the left, select Defaults, then Python, then check the 'Show command line' box, this will make it the default setting whenever you open a .py file, (this feature should really be on by default!)
Right Click --> Run File In Console
Done!
Looks like in version 2018.3, this option is now Run with Python console in Run/Debug Configurations:
What you're looking for is the feature called Execute Selection in Console which is described in section Loading Code from Editor Into Console of PyCharm's online help.
Select the script lines that you want to execute and press Shift+Alt+E
You can run the Find Action shortcut (Ctrl+Shift+A or ⌘+⇧+A on mac), then type run file, and choose the option Run file in Console.
In pycharm do:
Run>Edit Configuration>Show command line afterwards
Assuming your code is in file MySimpleCode.py you can simply say
run MySimpleCode
in the PyCharm console. This assumes that you have set your working directory properly; e.g. if MySimpleCode.py is located in d:\work on a Windows system you must execute
cd d:\work
first. In my opinion the other solutions miss what the post really wants: simply executing a file like from a DOS or Unix shell, or a .m script in MATLAB. No messing with imports, projects and so on. If you use CTRL SHIFT F10 your code gets executed, sure, but in a different environment, so you have no access to variables created in your code. I assume the question means that you want to do further work with the results of the script.
Explanation for people with MATLAB background: In most Python IDEs you have to configure an interpreter first in some kind of project. The MATLAB equivalent would be a master IDE where you can choose your MATLAB version for each project. This makes it possible to run your Python code on the CPU, your GPU or even an external NVIDIA board with different settings (after several days in the installation hell). For the beginner this is very confusing, because for simple code samples any "default" interpreter should suffice. Unfortunately this is not the case for Python (2 or 3? 2.x or 2.y? which package version?), and it will get worse as you progress (which 32 or 64 bit version of TensorFlow is available for Python 3.x? and so on).

How can I interact with rather long python scripts?

I love the IDLE. However, sometimes I have 100-200 line scripts and I want to sort of interactively debug/play with say, functions defined in foo.py instead of just calling python foo.py. Is there a way I can trigger IDLE in the context of my foo.py?
Insert this line into the script:
import pdb; pdb.set_trace()
Which will start the python debugger which lets you step through the script interactively, checking variables and such as you go.
I assume you are asking about how to enable debugging in Idle?
In the Python Shell window, choose Debugger from the Debug menu, then open foo.py and use the Run Model command. A Debug Control window opens, allowing you to step through the execution of foo.py; when execution is over, the prompt is still available for you to manually call functions, interact with objects or otherwise tinker with your application (and you will be still debugging the script).

Categories