Change windows command title programmatically and permanently - python

I can change the console title form a python program using ctypes.windll.kernel32.SetConsoleTitleW(some_new_title) but as soon as the program exits (or crashes) the title reverts to whatever it was before. Is there some way to make the new title stay even after the program exits? The reason I want this is because I have quite a lot of different python scripts running on different consoles and I want to be able to quickly identify them by name in my taskbar. This works perfectly while the programs are actually running, but if a few of them either finish or crash then I have a collection of console titles in my taskbar which are all identical.

Thanks to the clue from #Jon Clements...
Instead of launching my python script with this:
python myscript.py
I write a batch file mypy.bat which contains...
title %*
python %*
Then I run my script with:
mypy myscript.py
The name of the window remains as "myscript.py" even after the script exits.

Related

Running a python script in a Windows 10 powershell

I have a little python script that takes a single filename as a command line argument and writes a converted file. Not rocket science, it's 10s of lines long.
I can run that on windows from a cmd prompt simply by typing the name of the script. So for example:
C:\> CD \wheremyscriptis
C:\wheremyscriptis> myscript.py
and it runs fine. Without any arguments it spits out a little Usage message. Quite conventional.
Now we're using Powershell more and more and the first thing I notice in powershell is it won't run at all without an explicit directory, so in the above example I'd need to type .\myscript.py.
That's odd but you could get used to it, not a crisis.
But what happens now is the script runs in another window, which flashes up and disappears before youc an read the usage message.
Given the behavior is inconsistent across these contexts, what can we do inside the script to make the powershell context more usable. Is there a way to detect if we're running in some window that powershell threw up (which is itself weird) and then if so, pause before exiting to give a user a chance to read the usage message before the window disappears?

Visual Studio Code - python console

I'm using visual studio code with standard python extension, my issue is that when I run the code the python interpreter instantly closes right after and I only see the output which means that if I create some data structure I have to create it every single time. Is it possible to leave the console open after running the code and maybe running multiple files in the same python interpreter instance?
I used to use spyder which is entirely doing what you want (probably like PyCharm)...
Then I briefly tried VS Code, and it is quite easy to make it behave that way too.
First make sure you have an integrated terminal open (or do Ctrl+`, or View > Integrated Terminal), then in that terminal launch ipython.
Now, when you use the commands from Don Jayamanne's Python extension (Ctrl+Shift+P to open commands palette):
"Run Python File in terminal"
"Run select/line in Terminal"
It will run the line inside the ipython console directly. So running the entire file will call python module.py inside ipython, and thus fails.
So to make this work simply create settings to map which command is executed when "Run select/line in terminal":
Open Language specific settings (Shift+Ctrl+P, search "Configure Language specific Settings...")
Pick up Python
Now I would suggest to make change only in your workspace settings (top-right tab) to keep default behaviour in other cases
so add in WORKSPACE SETTINGS:
(keep in mind it is just a simple/stupid workaround)
{
"python.pythonPath": "run"
}
Now when runing whole file, it will use ipython function run within the ipython terminal that we launched, thus keeping all your workspace variables.
Also, if you run some line of code with "Run Select/Line in Terminal", the ipython session of that terminal keep all variables.
This allows live debugging, without actually going in the debug mode.
When you run a program, it runs until it ends. Then it closes. If you want it to stay live longer, you can make a program which does not stop until told so, e.g.
while True:
something = raw_input('Write something: ')
print('You wrote: %s' % something)
if something == 'bye':
print 'bye.'
break
This will run until user writes "bye".
I'm quite late to this conversation, but a workaround I use is to put a pass statement at the end of my file, then add a breakpoint to it. I then run it in the debugger and can access all of the variables etc.
This allows most of the functionality that I used to use in the PyCharm python terminal, such as exploring data structures, checking out methods, etc. Just remember that, if you want to make a multi-line statement (eg. for a loop), you need to use Shift-Enter to go to the next line otherwise it'll try to evaluate it immediately.

Running a simple script from desktop [duplicate]

This question already has answers here:
How do I run a Python program in the Command Prompt in Windows 7?
(24 answers)
Closed 7 years ago.
So I'm an extreme beginner to programming, just starting the Python class on Coursera. Using Python 2.7.10
Anyway, I made a simple print statement script in Notepad++
print "Hello World"
and saved as a python file on my desktop
newprog.py
However when I try to run it a cmd window appears and disappears and I'm not quite sure whats wrong.
The other question that this was linked as a duplicate to is about accessing python through the command prompt, which I don't have a problem with. From answers given it is now apparent to me that my dilemma was due to an erroneous belief that the interpreter would remain open after running whatever script I wrote.
Sounds like your program simply opened, ran and exited. So nothing was wrong, it just all happened a bit quick for you to see it.
You should run it from a command prompt or get an IDE like Pycharm, which will allow you to both write and run your script in one program.
To run from command prompt, use either Windows Key + R and type 'cmd' or click start and type 'cmd' into search box. Then you can drag your script to the command prompt window and press Enter to run it.
If you wanted to run it by double click, you'd need something to stop it from finishing until you'd read the message. To achieve this you can use the raw_input function, which waits for user input.
So your script would then look like
print "Hello World"
raw_input("Press Enter to exit")
Then you could double click and press enter when you are ready to exit.
Go to the command prompt window
python
then type in
execfile('path to newfile.py here')
Your file will now be executed
I'm running python 3.4.3. But it should be the same, I hope.
Go go "..\PythonXX\Lib\idlelib" and look for idle.pyw NOT idle.py and using the you're able to execute simple one line commands like the one you have up there.
From that you can also create a new file and do more complicated stuff.
If you create a shortcut to your desktop, you'll be able to access it easier.
Let me know if it helps, or at least correct path.
Your script is probably working and then finishing, the result is shown but not for long. I recommend opening the console and running your script from there, or you could use a simple batch file to run python scripts and then wait for a key press.
To open the console you can use the Windows key along the R key, Win-R (to run a new process) and write cmd, or you look for cmd in your Window's start menu.
With the console opened, you must locate the path where your script is, you can use the cd (Change Directory) to get there, for example:
cd C:\Users\your_name\Desktop
and then write:
python newprog.py
to run your script.
Another option is to use this simple batch file (save it as python34.bat or similar, but the extension must be .bat, put it wherever you like):
#ECHO OFF
C:\Python34\python.exe %*
pause
#ECHO ON
And then use that to run your scripts by right clicking a python script file, open with (run with) and use this batch script as default (if you want). Also, if you have another version of Python, or is installed elsewhere, you must change the "C:\Python34\" part.
This is a computer we're talking about here. It might take you triple the time it takes a computer to multiple two numbers for example. With this notion in mind, the computer quickly prints then exits.
raw_input() # at the end of script wait for user to supply input, delaying script exit

launch external shell python instance in shell from python

I'd like to call a separate non-child python program from a python script and have it run externally in a new shell instance. The original python script doesn't need to be aware of the instance it launches, it shouldn't block when the launched process is running and shouldn't care if it dies. This is what I have tried which returns no error but seems to do nothing...
import subprocess
python_path = '/usr/bin/python'
args = [python_path, '&']
p = subprocess.Popen(args, shell=True)
What should I be doing differently
EDIT
The reason for doing this is I have an application with a built in version of python, I have written some python tools that should be run separately alongside this application but there is no assurance that the user will have python installed on their system outside the application with the builtin version I'm using. Because of this I can get the python binary path from the built in version programatically and I'd like to launch an external version of the built in python. This eliminates the need for the user to install python themselves. So in essence I need a simple way to call an external python script using my current running version of python programatically.
I don't need to catch any output into the original program, in fact once launched I'd like it to have nothing to do with the original program
EDIT 2
So it seems that my original question was very unclear so here are more details, I think I was trying to over simplify the question:
I'm running OSX but the code should also work on windows machines.
The main application that has a built in version of CPython is a compiled c++ application that ships with a python framework that it uses at runtime. You can launch the embedded version of this version of python by doing this in a Terminal window on OSX
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python
From my main application I'd like to be able to run a command in the version of python embedded in the main app that launches an external copy of a python script using the above python version just like I would if I did the following command in a Terminal window. The new launched orphan process should have its own Terminal window so the user can interact with it.
/my_main_app/Contents/Frameworks/Python.framework/Versions/2.7/bin/python my_python_script
I would like the child python instance not to block the main application and I'd like it to have its own terminal window so the user can interact with it. The main application doesn't need to be aware of the child once its launched in any way. The only reason I would do this is to automate launching an external application using a Terminal for the user
If you're trying to launch a new terminal window to run a new Python in (which isn't what your question asks for, but from a comment it sounds like it's what you actually want):
You can't. At least not in a general-purpose, cross-platform way.
Python is just a command-line program that runs with whatever stdin/stdout/stderr it's given. If those happen to be from a terminal, then it's running in a terminal. It doesn't know anything about the terminal beyond that.
If you need to do this for some specific platform and some specific terminal program—e.g., Terminal.app on OS X, iTerm on OS X, the "DOS prompt" on Windows, gnome-terminal on any X11 system, etc.—that's generally doable, but the way to do it is by launching or scripting the terminal program and telling it to open a new window and run Python in that window. And, needless to say, they all have completely different ways of doing that.
And even then, it's not going to be possible in all cases. For example, if you ssh in to a remote machine and run Python on that machine, there is no way it can reach back to your machine and open a new terminal window.
On most platforms that have multiple possible terminals, you can write some heuristic code that figures out which terminal you're currently running under by just walking os.getppid() until you find something that looks like a terminal you know how to deal with (and if you get to init/launchd/etc. without finding one, then you weren't running in a terminal).
The problem is that you're running Python with the argument &. Python has no idea what to do with that. It's like typing this at the shell:
/usr/bin/python '&'
In fact, if you pay attention, you're almost certainly getting something like this through your stderr:
python: can't open file '&': [Errno 2] No such file or directory
… which is exactly what you'd get from doing the equivalent at the shell.
What you presumably wanted was the equivalent of this shell command:
/usr/bin/python &
But the & there isn't an argument at all, it's part of sh syntax. The subprocess module doesn't know anything about sh syntax, and you're telling it not to use a shell, so there's nobody to interpret that &.
You could tell subprocess to use a shell, so it can do this for you:
cmdline = '{} &'.format(python_path)
p = subprocess.Popen(cmdline, shell=True)
But really, there's no good reason to. Just opening a subprocess and not calling communicate or wait on it already effectively "puts it in the background", just like & does on the shell. So:
args = [python_path]
p = subprocess.Popen(args)
This will start a new Python interpreter that sits there running in the background, trying to use the same stdin/stdout/stderr as your parent. I'm not sure why you want that, but it's the same thing that using & in the shell would have done.
Actually I think there might be a solution to your problem, I found a useful solution at another question here.
This way subprocess.popen starts a new python shell instance and runs the second script from there. It worked perfectly for me on Windows 10.
You can try using screen command
with this command a new shell instance created and the current instance runs in the background.
# screen; python script1.py
After running above command, a new shell prompt will be seen where we can run another script and script1.py will be running in the background.
Hope it helps.

Command window flashing only when os.system is being used

I have a weird issue on a friends machine where when they run my script, it only flashes the command window when it hits a line that does something with os.system. It seems to not show the command window at all otherwise. Not showing is fine, but my script does a large process and it causes the window to flash a lot.
Normally on my machine, when I open the script (that launches a gui with tkinter) the command window will open as well in the back. This is what I am trying to get my friends to do, but I do not know what would cause the command window to not show. Is there a setting within python somewhere that doesn't show the command window (unless of course it needs to run a process in it)?
Edit: Ok I did a really lame hack to fix this. Apparently all he .py files got associated with pythonw. I was unable to get this association changed (even going through the command prompt ASSOC) So I just did a silly renamed of the pythonw to old_pythonw, and renamed the python.exe to pythonw.exe. Yes, really silly but no time to argue with windows about file associations.

Categories

Resources