How to remove "press enter to continue" when running Powershell within Python - python

Edited* Solution: Remove "pause".
I'm running a python script which calls upon powershell to execute a line of code:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;pause', shell=True)
download()
The problem was that after executing, it would output "Press Enter to continue..." This interrupts the program.*in my original example I forgot to include the ";pause" which is what turned out to be what was causing the interruption in the program, as kindly pointed out by the marked answer.
Below is the fixed line of code which does not prompt "press enter to continue" after running:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;kill $pid', shell=True)
download()
Apologies for confusion caused by the original post. Thanks for the help.

PowerShell normally exits unless you specify -NoExit at the commandline. Even then it will not include the message you are seeing unless you add a pause at the end instead. Even so, I would expect your command to look more like
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe & {yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4}'
My guess this has more to do with Python, though I have not encountered it before...have you tried executing the PowerShell line from another commandline (cmd on Windows or bash on Linux/Mac or another favourite) to verify that you get the same result independently of Python?
Another possibility is that it is the yt-dlp tool that you are using that has the pause effect (I am not familiar with the tool). Is it a PowerShell module? Or is it something that can be run on the commandline and you don't need PowerShell as a middleman anyway? Would it have a "silent" or "-q" argument, or another more relevant argument?

Related

Issue with command prompt (windows) and python script after restarting script

I am trying to write a CLI program with python in windows. I recently came across an issue with argparse and my work-around was to clear the command prompt and re-run my script with the same arguments using this code:
sys.stdout.flush
os.execl(sys.executable, 'python', __file__, *sys.argv[1:])
This works perfectly until I try to input something into my program. I have this perpetual loop in my code which allows me to input a string and have it echoed back to me:
while True:
action = input("> ")
print(f'typed {action}')
but once I reach that point in the code, it does not work, this is my output:
This is the expected output up until after the red "Ready."
for some reason, the command prompt alternates between an input to my script, and an input to the command prompt, which are both prefaced with the wrong text, the ">" should be an input to my script, but that input is being sent to the command prompt, and the "...\raspi>" should be an input to the command prompt, but that input is being sent to my script. Anyone have any ideas as to why this is happening? Why it's alternating between my script and regular command prompt?
The solution I came to was to realize that the cprint() function of the colorama.py library does not return text and instead just calls the print function (I should have been able to deduce that through the name of the function). So all I had to do was to not set the description of my parser to a cprint() function and instead call cprint() when it's needed.

Interactively communicating with a FORTRAN shell program

DAOPHOT is a FORTRAN-written software for performing astronomy tasks in images. A typical flow of its usage is:
Open a terminal (gnome-terminal in my case) and run ./daophot. I'm now within DAOPHOT's shell.
Prompts the user for a command, let's say ATTACH to input an image file. DAOPHOT runs and prompts the user again for more commands.
User gives another command, let's say PHOTOMETRY. DAOPHOT runs and prompts the user again.
For every command the user gives, DAOPHOT runs and prompts again and again until exit is typed. For my case, I have three specific commands that will run one after another, without variation (ATTACH, PHOTOMETRY and PSF, with the latter maybe run more than once).
Right now I'm simply trying to ATTACH a file. What I have tried:
Using subprocess, as seen/asked here and here:
import subprocess
p = subprocess.Popen(["gnome-terminal","--disable-factory","--","./daophot"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.write(input("ATTACH file.fits"))
For this case, DAOPHOT's shell opens but the ATTACH command is not executed. I close the shell and the string "ATTACH file.fits" appears in the IPython terminal, ending the subprocess. I've tried also to use p.communicate(input=input("ATTACH file.fits")), but got the same result.
Using pexpect, as seen/asked here and here:
import pexpect
p = pexpect.spawn("gnome-terminal --disable factory -- ./daophot")
p.expect(pexpect.EOF)
p.sendline("ATTACH file.fits")
In this case, DAOPHOT's shell opens but the ATTACH command is not accounted for as an input.
Finally, a DAOPHOT wrapper already exists, but the idea is to have this automatically and interactive Python version in our lab, so that we can change later if needed.
From what I understand in terms of pipelines, ./daophot is a subsubprocess runnning inside gnome-terminal, so when I use e.g. p.stdin.write(input("ATTACH file.fits") I am actually inputing this command into gnome-terminal, and not into ./daophot.
Any help is much appreciated.

Python: Check if Program is being closed

all.
Is there a way, using Python, to check if the script that is currently running is requested to close? For example, If I press the X-Button (close program button) on the top-right to close it, or end the script in any other way, can the script do some code before it ends? Example:
# script goes here...
if Script_To_Be_Closed: # replace this with an actual line of code.
do_stuff
There are multiple options you may use, like trapping keyboardinterrupts, but the simplest is atexit, which executes a function whenever a scripts is ended (except of a hard process kill indeed).
import atexit
def my_exit_function(some_argument):
// Your exit code goes here
print(some_argument)
if __name__ == '__main__':
atexit.register(my_exit_function, 'some argument', )
// Your script goes here
You can use a shell script to do the job
You can see the script command shown below which calls itself after executing the command to run the python file. once the python file is closed the next line will force the python command to run again. you can also customise the behaviour the way you want.
main.py
#!/bin/bash
python3 ./main.py
source ./infiniteRun.sh
If you need to stop the job just edit the file and remove the last line source ./infiniteRun.sh and save the file.

Call to several batch files through CMD doesn't block

I'm trying to call several install.bat files one after another with Python trough CMD.
It is necessary that each bat file be displayed in an interactive console window because it asks for some users instructions and that the python program only resume after each CMD process is resolved
Each install.bat file can take a pretty long time to finish its process.
My code is the following :
for game in games :
print("----------- Starting conversion for %s -----------" %game)
subprocess.call("start cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game), shell=True)
print("end")
But the console windows inside the shell are launched all at once and the "end" message appears event before any of them is finished, whereas I would like them appearing one by one and not go to the n+1 one until the n one is finished and the console window closed (either by user or automatically /K or /C then).
I understand this is some problems using CMD as call should be blocking. How to resolve that? Additionally, if possible how to keep it exactly the same and add 'Y' and 'Y' as default user input?
The most common way to start a batch file (or more generally a CLI command) if to pass it as an argument to cmd /c. After you comment I can assume that you need to use start to force the creation of a (new) command window.
In that case the correct way is to add the /wait option to the start command: it will force the start command to wait the end of its subprocess:
subprocess.call("start /W cmd /C " + "Install.bat", cwd=os.path.join(gamesDosDir,game),
shell=True)
But #eryksun proposed a far cleaner way. On Windows, .bat files can be executed without shell = True, and creationflags=CREATE_NEW_CONSOLE is enough to ensure a new console is created. So above line could simply become:
subprocess.call("Install.bat", cwd=os.path.join(gamesDosDir,game),
creationflags = subprocess.CREATE_NEW_CONSOLE)

Programmatically injecting command into Python Cmd's cmdloop

Using Python Cmd2 module (inherits from Cmd) to create a MyCmd CLI for my program. In most cases, I am just using my script normally with the built-in commands. The ‘quit’ command is implemented to do some cleanup for the script and subsequently exit. The Cmd2 module waits for input via the raw_input.
In a specific case, I want to programmatically invoke ‘quit’ instead of issuing it at the command line. This is done via a separate thread where a REST API translates a ‘quit’ POST to invoke quit on the main thread of the script.
I found a couple of SO questions that want to do something similar, but not exactly like this. I tried to follow the below example, but it didn’t work:
Python StringIO - selectively place data into stdin
Then I tried something simple. Basically did the below from the thread:
sys.stdin = StringIO('quit\n')
sys.stdin.flush()
It seems that the word 'quit' was injected, but the script would not do its clean exit. However, I could go back to the command line and simply press Enter, which would trigger the cleanup and exit process. Not sure why ‘\n’ was not being interpreted as Enter.
My cmd is simply invoked in the below manner:
mycmd = MyCmd()
mycmd.cmdloop()
How can I properly inject ‘quit’ into the cmdloop of Cmd?
Have you tried the cmd.onecmd("quit") method? I think it can be used to inject commands in the interpreter.

Categories