I am attempting to use the os module in Python to clear the screen. As I'm using Fedora, the standard console command to clear the display is clear. When I type the following into a .py file:
from os import system
system("clear")
print("Hello world")
and run the file by opening a standard Terminal window and calling the file directly using the python shell command, it all works fine. However, if I type the same code into Ninja-IDE and execute it in the embedded console there, what comes out is the message "TERM environment variable not set" wherever I wanted to clear the screen.
Now, I'm aware that I can set the TERM environment variable if it is non-existant using something like this:
import os
try:
print(os.environ['TERM'])
except KeyError:
os.environ['TERM'] = foo
but, I'm unsure exactly what to set it to so that it works in Ninja-IDE. I've tried some of the obvious - xterm, xterm-256color, konsole - but they do not work for Ninja-IDE. Which leads to my question: what is the appropriate value of the TERM environment variable corresponding to the embedded console in Ninja-IDE? Or, alternatively, is it possible to tell Ninja-IDE to invoke an external terminal (such as xterm) when executing code, rather than using its own inbuilt console?
The answer is simple. It is caused by os.system. Simply add import system to your code and it is done, like this:
import os
import system
import shutil
import datetime
os.system('clear')
Related
I am just getting started with Python.
How do I call a test script from C:\X\Y\Z directory when in Python interpreter command line in interactive mode? How do I specify the full path for the file when it is not in the current working directory?
I can call a test script when using the windows run command with "python -i c:\X\Y\Z\filename.py" and it runs fine. But I want to be able to call it form the Python terminal with the ">>>" prompt.
(I searched and searched for two hours and could not find an answer to this, although it seems like it should be a common question for a beginner and an easy thing to do.)
Thanks
Since you are using backslashes for the file path, python interprets those as "escape characters." When writing the file path in Python, make sure to use forward slashes.
with open("C:/X/Y/Z/filename.py", "r") as file:
exec(file.read())
Double backslashes also work, but I prefer the cleaner look of forward slashes.
If you want to import it into the REPL:
import sys
sys.path.append('c:\X\Y\Z')
import filename
If you want to execute code from a file within the interpreter, you can use execfile
execfile('C:/X/Y/Z/filename.py')
(/ works as path separator in all operating systems, if you use \, you need to escape them ('C:\\X\\Y\\Z\\filename.py')or use raw string literal (r'C:\X\Y\Z\filename.py'))
If you are using IPython (and you should use, it's much more useful than vanilla interactive Python), you can use magic function run (or with % prefix: %run):
run C:\\X\\Y\\Z\\filename.py
%run C:\\X\\Y\\Z\\filename.py
See this link for more information about magic functions.
And by the way, it has even auto completion of filenames.
Exec the heck out of it
Python 2.x:
execfile("C:\\X\Y\\Z")
Python 3+:
with open("C:\\X\Y\\Z", "r") as f:
exec(f.read())
Still, that is very bad practice - it executes code from a string (at some point), instead of using preferred and safer way of importing modules. Still, when you import module and have some of its code after "-f __name__ == '__main__':", that parts won't work (because __name__ in imported module won't be __main__, and it would be, if you ran it as single script).
It is bad for many reasons, in some sense strongly connected to Zen of Python, but if you're beginner, this should speak to you:
When you do anything in interactive mode, you work on some namespace (this term is very important for understanding python, if you don't know it, check it in python language reference). When you exec()/execfile() something without providing globals()/locals(), you may end up with modified namespace.
Modified namespace?
What does it mean? Lets have a script like that:
radius = 3
def field_of_circle(r):
return r*r*3.14
print(field_of_circle(radius))
Now, you have following session:
>>>radius = 5
>>>execfile("script_above.py")
28.26
>>>print(radius)
3
You see what happens? Variables defined by you in interactive session will get overwritten by values from end of script. The same goes for modifying already imported external modules. Lets have a very simple module:
x = 1
and executed script:
import very_simple_module
very_simple_module.x = 3
Now, here's a interpreter interactive session:
>>>import very_simple_module
>>>print(very_simple_module.x)
1
>>>execfile("executed_script.py")
>>>print(very_simple_module.x)
3
Run another interpreter
Interactive sessions are very useful for many things, but not for many things, but running python scripts is not one of them.
Unless... you wanna play tough and use python shell as system shell. Then, you can use subprocess (in standard library) or sh (which can be found on PyPI):
>>>import subprocess
>>>subprocess.call(["python", "C:\\X\Y\\Z"], shell=True)
>>>from sh import python
>>>python("C:\\X\Y\\Z")
Those won't have this problem with modifying interactive interpreters namespace
See script as module
Also, there is one more option: in interactive session add directory with script to pythonpath, and import module named as script:
>>>import sys
>>>if "C:\\X\\Y" not in sys.path:
sys.path.append("C:\\X\\Y")
>>>import Z
Remember that directory in which interpreter was started is automatically on pythonpath, so if you've ran python in the same directory as your script, you just have to use 3rd of lines above.
Interpreters namespace won't change, but code after "-f __name__ == '__main__':" won't be executed. Still you can access scripts variables:
>>>radius = 5
>>>import first_example_script
>>>print(radius)
5
>>>print(first_example_script.radius)
3
Also, you can have module name conflict. For example, if your script was sys.py, then this solution will work, because python will import builtin sys module before yours.
I just setup PyDev with Eclipse, but I'm a little confused. I thought that in the console I would be able to type certain commands such as print("Hello World") and directly observe the result without having to incorporate that in any sort of file.
The reason I would like this is because it would allow me to test functions real quick before using them in scripts, and I'm also following a tutorial which tells me to check if NumPy is installed by typing import NumPy in the command line.
Thanks!
There should be an interactive console in PyDev.
Try Ctrl+Alt+Enter or Cmd+Alt+Enter.
Open up terminal and type python then it should load python shell then type
import numpy
I have used pydev and find its easier just to use terminal to run small commands
I have a tkinter script, which runs just fine in IDLE. However, when I double click the .py-file from Windows Explorer, the console window flashes half a second and then it exits.
I was able to screenprint the console window. It says:
...etc.etc...
NameError: global name 'simpledialog' is not defined
simpledialog is a module in tkinter which I use in my script. As I do from tkinter import *, there is no need to explicitly write tkinter.simpledialog.
It works in IDLE, why not as .py?
IDLE uses Tkinter as its graphical environment. It is possible that your code is relying on a side effect of an import by IDLE itself. This is especially true if you use IDLE without a subprocess.
The simpledialog module does not import when using from tkinter import *.
Try adding this to your code:
import tkinter.simpledialog as simpledialog
Have you updated your PATH environment variable so that your Python executable is found? You can find more information on how to do here - Using Python on Windows
But you basically need to make sure that the folder containing python.exe (e.g. C:\Python32) is displayed when you type the following command from a prompt:
echo %PATH%
I had exactly the same problem with one of my scripts utilizing Tkinter.
Adding call to mainloop() fixed the issue.
See this tutorial for an example: [http://sebsauvage.net/python/gui/#import1
In my case, in the init function I have
def __init__(self,Width=400, Height=400):
# Create GUI window ------------------------------
win = Tk()
...
in the end of init I added:
win.mainloop()
Now it works by just running the file.
Hope this helps
Similar trouble for me just now, in my first week with python. But I dimly remembered a similar problem with a simple early test script and thought the trouble then was # comments.
So I tried that with my Tkinter infused .py script. It ran fine in IDLE as you say, then only flashed when clicked in windows. But there were a couple # commented lines at the top of file.
I took them all out and it now runs no sweat directly in windows. Have a look .. for #.
Sorry, can't seem to delete this post. Now the files work #comments included. Don't know what's up with that. ..
I found that changing the executable py file to a file.pyw fixed the problem. This tells python to execute it using the pythonw.exe which runs the script without the terminal/console in the background.
Not sure why this works, perhaps some screwed up environment variables from a previous python installation.
Changing the file's extension to pyw instead of py might solve the problem
If you've used Ruby on Rails, I'm thinking of the feature where the user types
'rails console'
and instantly gets a Ruby console with rails and the current app already loaded.
I want to make something like this for a python program I'm working on, does anyone know how I would get to type say,
'python myPythonConsole.py'
and open up a regular python interpreter but with my program and all its dependencies loaded?
If I understand you correctly then you might want python -i myPythonConsole.py. It gives you a console when the script has finished so you have to run your application in a different thread.
To create a console in a script you would use the code module.
If you are using IPython (if you are not you should, it is an awesome python shell with TAB completion and many shortcuts) it is possible to set up profiles, which basically are named configurations.
Each configuration can import modules (and do other stuff) at startup.
Django does this with its "shell" command:
./manage.py shell
will open a Python shell with your Django settings loaded so you can import your project code interactively.
Source: http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py
The real answer here is to use the PYTHONSTARTUP environment variable. See the tutorial section The interactive startup file.
Do your custom imports in a file interpreter.py, and configure
PYTHONSTARTUP=/path/to/interpreter.py
Next time your start Python, the custom code will be executed before you're dropped in the REPL shell.
Here's my customization:
import os
import sys
from pathlib import Path
from pprint import pprint
pp = pprint
P = Path
version = ".".join(str(number) for number in sys.version_info[0:3])
print(f"\nCustomized Python interpreter v{version} running from {sys.prefix}")
When I use IPython along with the -wthread option, it spawns a python subprocess, which appears as a Mac OS X application.
My problem is that when I send commands to that application (for example plotting with matplotlib), the window is updated behind all my other windows. I would like to be able to call a python command to switch this python window to the front (I do that manually with ⌘-tab, but I have to find the python application first, and there might be several ones).
Is there a python script to detect which application IPython has spawned, and how to then automatically switch to it in OS X?
(I'm stating the problem in OS X, but the issue should be similar on other systems).
Edit: let me break this down in two problems:
how to know which Mac OS X application python is running in? (probably possible with some IPython witchery)
how to tell Mac OS X to put the focus on that application? (maybe using applescript)
Could be either:
Making a new python script that tracks grandchild processes of another script might be tricky. The IPython documentation has an example to monitor spawned processes by pid; JobControl. JobControl only kills the processes but I imagine adding a command to change window focus would be fairly easy.
From what I've read, the Tk gui does not properly set window focus on macs. If your 'matplotlib' or otherwise uses the Tk gui, this may be the problem. -source-
I am not very familiar with OS X, so either run with those, clarify your situation or let me know if I'm too far off.
Here is my full solution, with an IPython magic function.
Install appscript (see this question about switching apps programmatically in OS X), and put the following code in a script called activate.py in your ~/.ipython folder.
import appscript
import sys
appscript.app(pid=int(sys.argv[1])).activate()
Now, edit your ~/.ipython/ipy_user_conf.py configuration file and define the magic function:
def wxactivate(self, arg):
import wx
pid = wx.GetProcessId()
ip = self.api
import os
here = os.path.dirname(__file__)
import subprocess
subprocess.Popen([os.path.join(here, 'activate.py'), str(pid)])
Now you just have to register this magic IPython function by putting the following somewhere in that same configuration file:
ip.expose_magic('wxactivate', wxactivate)
Now, after you run IPython -wthread, you can call %wxactivate and you will switch to the corresponding Python application!
(note that the reason why one has to run the call to appscript's activate() in another process in not clear to me; it may have to do with some threading problem... any explanation would be appreciatated)