I would like to be able to run a python script from a .ps1 file without the terminal window showing up to run the script. I would think that there is some extra command I can put at the end to make it run windowless, but I am not sure what it is.
The only code I have in the ps1 file is to execute the python script by linking the path.
I do not want to run the code some way else, it has to be from a ps1 script since I will be adding to it eventually to have more features. I also would rather not have to change the file to a .pyw if possible.
E:/script.py
*Note - I ran the file from a different drive this time, but I want it to be from E:/ like I have in my code.
What I don't want to show up:
In a comment you state:
im using run (WIN + R) and this command: powershell -w h iex (E:\a.ps1)
-w h is short for -WindowStyle Hidden
iex is short for Invoke-Expression, which is not needed here - and should generally be avoided: see this answer.
Note: While this does make the console window that the PowerShell session itself runs in invisible, the window becomes invisible only after briefly showing first.
To avoid this brief flashing of the console window, powershell.exe must be launched indirectly, namely via a GUI-subsystem application that launches it with a hidden window; the bottom section of this answer discusses options.
Also note that supporting this directly in the future is planned, but will likely only be implemented for the CLI of PowerShell (Core) 7+, pwsh.exe - see GitHub issue #3028.
With that out of the way:
Console applications (including .ps1 scripts) invoked directly from a hidden PowerShell session run hidden too, because they run directly in the hidden console window.
By contrast, any GUI applications or applications of either type invoked via Start-Process run visibly.
While you can generally use Start-Process -WindowStyle Hidden to run GUI applications invisibly as well, this, unfortunately, does not seem to work with .pyw files, i.e. pythonw.exe-launched scripts, which still run visibly.[1]
By default, .py files invoked directly execute via py.exe, which is a console application.
Strangely, your screen shot suggests that it is not in your case.
py.exe is normally just a launcher for the true console Python executable (allowing you to switch between v2 and v3 versions of Python with py -2 ... and py -3 ...), python.exe, so as a workaround you can try the following (use a full path to python.exe, if needed):
Modify your E:\a.ps1 script to explicitly invoke your .py script with python.exe:
python.exe E:\script.py
Then launch your invisible PowerShell session as before, except with improved syntax:
# Short for:
# powershell.exe -WindowStyle Hidden -File E:\a.ps1
powershell -w h -f E:\a.ps1
If that doesn't help, consider reinstalling Python.
[1] I'm guessing this is because the windows potentially created by the .pyw scripts themselves are unrelated to the (invisible) main window of the pythonw.exe GUI-subsystem executable.
Start-Process python -ArgumentList "python-script-file-path" -NoNewWindow
Lots of excellent info here.
Related
I used to run Python scripts from my Windows command line, and all the prints were printed in the same console. Now something happened on my machine (Windows 10), and when I launch a Python script from the command line (i.e. open a Command Prompt and run python <my_script.py>), Windows opens a new window (titled with the absolute path of python.exe). This windows closes automatically at the end of the execution, so that I can't see the output.
How do I go back to printing output in the same command prompt window from which I run the script?
Not sure how useful this will be but I had this same problem, found this thread, and realized that the new console window was opening up when I omitted 'python' from the command.
>python myscript.py
shows the output right in the terminal where I typed the command, but
>myscript.py
opens the new console window and closes it immediately after the script runs.
It's odd but it very likely a windows setup issue as python is an exe. If memory serves windows will spawn on a > run command so checking the way python is booting will help.
Unfortunately it could be a range of issues, so some steps towards victory:
What happen when you just type python into the cmd? If it simply starts the input >>> - it means your python setup is fine. If a cmd window spawns and disappears it may be a windows permissions issue.
Try running your script with -i flag: python -i script.py. This drops you into the repl when the app completes - displaying your output.
Ensure you're using the native flavour of the cmd to test. Ensuring any command app or IDE isn't injecting a start command or weird /K (spawn new window) flag.
Hope it helps.
In my computer this was caused by Windows not knowing what program a .py file was associated with. I solved this by going to:
Control Panel -> Programs -> Default Programs -> Associate a file type or protocol with a program (Scroll down) and choose "Choose default apps by file type" Scroll down until you see ".py" and choose the correct
Python interpreter.
Simply: last row on the end of your program maybe this:
input("\nIf you whish end the program press any key ...")
...and your program wait for the key and you see your outcome
I am trying to use Curses in PyDev in Eclipse in Win7.
I have installed Python 3.2 (64bit) and curses-2.2.win-amd64-py3.2. When I input the following testing codes into PyDev:
import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()
It did not show any syntax error, so I think the curses was installed correctly.
However, when I ran it as Python Run, the output showed: Redirection is not supported. I do not know where this problem comes from. I googled a lot but can't find related information.
Recent PyCharm versions (I am currently running 2017.2, not sure when this option was added, or if it has been there the entire time) have the option "Emulate terminal in output console". Curses works with this option checked.
You cannot expect to use curses with a non-terminal.
Probably you get this because you are running the script from inside an IDE, like PyCharm or any other.
All IDEs do provide consoles that are not terminals, so that's where the problem comes from.
For a Pycharm user the solution given by codeape works fine :
Snapshot
You can't use any IDE to run python files with the curses package. I used to run in pycharm and naturally couldn't run.
Change to the command line to run:
for testing follow my following steps
on desktop open notepad and copy paste the code and save it as filename.py
open command line change directory to desktop use below command cd Desktop and hit enter type python example.py and hit enter, your program will definitely run
My workaround is to create a Run Configuration that calls a curses script. The little overhead is worth not having to switch to the terminal and manually run the script hundreds of times a session. I use Intellij but I imagine the process should be similar in PyCharm.
The desired result is the convenience of a button to run the script:
First create a script that calls the entry script, for instance:
ptyhon name-of-script.py
Then, to create a configuration for each script:
Go to Edit configuration.
Click the plus button and add a Shell Script.
Enter the path to a shell script.
Here is a picture of a directory with a couple of sample scripts.
I use this process to view my progress. My curses scripts are very modest so fortunately I can live without a debugger.
I am trying to call an executable at startup, which will call another executable itself. For the first part, I simply added the path to the executable to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, which works, my executable is called at startup.
The latter contains, among others, these lines :
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
proc = subprocess.Popen(command, startupinfo=startupinfo)
However, a command shell (cmd) pops when the computer starts. Everything works fine, but it is visible instead of hidden... So basically, how do I hide this command shell ?
When using ProcessExplorer, I have the following hierarchy :
+ System
|_ Interrupts
|_ smss.exe
|_ some processes...
+ explorer.exe
|_ some processes...
|_ MYSCRIPT.EXE
Here is the sequence I try to achieve :
I create an ISO file containing all the Python executable I want to run on the VM. One of them (master.exe) calls the others.
I create a VM which automatically mount the latter
The VM, which was prepared, has a scheduled task which calls D:\master.exe
master.exe (among other tasks which are not our concern here) adds the value D:\myscript.exe to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
The VM reboots
D:\myscript.exe is run (and it works fine and as attended), but it does run in a command prompt, which I would like to be invisible.
This is a typical problem Python-programmers encounter - and therefore, a solution is offered by Python itself. It has been asked on SO many times, e.g., here, but for you, the problem is a little more complicated.
It's all about whether you use python.exe or pythonw.exe to run your script. For the first one, a console is opened, for the second it's not.
As you use compiled scripts, you have to tell "the compiler" which version you want to use. Assuming you are using py2exe, you can have a look at this post on SO. Here it is explained in detail how to proceed.
The console window that is being opened probably belongs to the Python process running your script. Show us the entry in the registry running your script.
If you run a console program, Windows will create a console window. "python.exe" is a console program.
If you don't want a console window, you can run your Python script with "pythonw.exe" rather than "python.exe".
You can compile it to exe format. When I encounter that problem,
I used py2exe to compile python file to invisible executible.
All you have to do, is to change setup.py file(used to compile), from
setup(console=['__main__.py'], options={"py2exe":{"includes":["sip"]}})
to
setup(windows=['__main__.py'], options={"py2exe":{"includes":["sip"]}})
I had the same issue and I used Pyinstaller.
Pyinstaller is a smart cross platform tool to compile .py file into standalone executable.
Install it via:
pip install pyinstaller (more information here)
Use the following command to hide the console (to make your script a process):
pyinstaller yourfilename.py -F --windowed
(with "-F" flag you'll get a single .exe file and with "--windowed" flag the console will be hidden)
I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using /cygdrive/c/Python26/python.exe myfile.py rather than python myfile.exe.
This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't print until execution finishes. It works fine running in Windows Python from explorer.exe or cmd.exe, and it works in Cygwin using the Cygwin-installed Python (/bin/python.exe).
Is there a workaround for this? The important thing is to be able to run the Windows version, but I'd like to do it all from with Bash.
The real problem is that when you run a command in any of the Cygwin terminal programs like mintty, they don't act as Windows Consoles. Only Windows Console-based ones like CMD or Console2 do that. So, with Cygwin terminals the Windows python.exe doesn't think it is talking to an interactive console.
That leads to buffering output instead of flushing buffers on every line as is done in interactive sessions. That is why Amro's adding the flush() on every line fixes the symptom, but means changing the code.
One solution without changing the code is to turn off buffering in Python using the '-u' flag on the command line or setting the PYTHONUNBUFFERED environment variable.
export PYTHONUNBUFFERED=1
/cydrive/c/Python27/python.exe foo.py
or
/cydrive/c/Python27/python.exe -u foo.py
or run in interactive mode
/cydrive/c/Python27/python.exe -i foo.py
You will also not be able to run the Windows python.exe interactive mode in the Cygwin terminal. It will not bring up an interactive session, but will just hang. I find the best solution seems to be to use 'cygstart' (better than using the '-i' option):
cygstart /cygdrive/c/Python27/python.exe
And that seems to work with ipython as well (if installed):
cygstart /cygdrive/c/Python27/Scripts/ipython.exe
Not answering the initial question, but for those who want to use Python interactive session from within Cygwin terminal (for example in mintty) - start Python with "-i" option to tell it explicitly that it needs to run in interactive mode:
$ python -i
The neat way is also to create an alias in your .bashrc (knowing that it is only read for interactive terminal sessions anyway):
alias python='python -i'
Otherwise, Python will not know that it runs in the console, because all Cygwin pty-based terminals (mintty, rxvt and xterm) are recognized as pipes by Windows, not as the console. Therefore, Python thinks there is no console and enters non-interactive mode. So, if you still want interactive mode instead, you need to explicitly tell Python to use it. However, it still won't behave as it normally should - one still won't be able to use HOME or LEFT ARROW keys, and so on.
Perhaps if you flush the output
import sys
V = range(100000)
for x in V:
print x
sys.stdout.flush()
How do I run a Python file from the Windows Command Line (cmd.exe) so that I won't have to re-enter the code each time?
Wouldn't you simply save your Python code into a file, and then execute that file using Python?
Save your code into a file called Test.py.
And then run it?
$ C:\Python24\Python.exe C:\Temp\Test.py
If you don't want to install an IDE, you can also use IDLE which includes a Python editor and a console to test things out, this is part of the standard installation.
If you installed the python.org version, you will see an IDLE (Python GUI) in your start menu. I would recommend adding it to your Quick Launch or your desktop - whatever you are most familiar with. Then right-click on the shortcut you have created and change the "Start in" directory to your project directory or a place you can mess with, not the installation directory which is the default place and probably a bad idea.
When you double-click the shortcut it will launch IDLE, a console in which you can type in Python command and have history, completion, colours and so on. You can also start an editor to create a program file (like mentioned in the other posts). There is even a debugger.
If you saved your application in "test.py", you can start it from the editor itself. Or from the console with execfile("test.py"), import test (if that is a module), or finally from the debugger.
If you put the Python executable (python.exe) on your path, you can invoke your script using python script.py where script.py is the Python file that you want to execute.
Open a command prompt, by pressing Win+R and writing cmd in that , navigate to the script directory , and write : python script.py
A good tool to have is the IPython shell. Not only can it run your program (%run command), but it offers also many tools for using Python interactively in an efficient manner (automatic completion, syntax coloring, quick access to the documentation, good interaction with Matplotlib,…). After you install it, you'll have access to its shell in the Start menu.
You need to create environment variables. Follow the instructions here: http://www.voidspace.org.uk/python/articles/command_line.shtml#environment-variables
In DOS you can use edit to create/modify text files, then execute them by typing python [yourfile]