This is a sample code snippet which reproduces the issue I'm facing:
import subprocess
ctb_path = "\"C:\\Program Files\\Cold Turkey\\Cold Turkey Blocker.exe\""
exception = input("Enter the exception phrase: ")
subprocess.run(f'{ctb_path} -add Distractions -exception \"*{exception}*\"', check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
choice = input("Enter your choice between 1 & 2: ")
Here, I'm not asked for an input because a newline has been accepted instead and successfully exited the program. What are the possible reasons this may occur? How can it be fixed?
Refer this for Cold Turkey Blocker's User Guide.
Related
trying to use python to automate a usage of a command line application called slsk-cli
manually, the procedure is straight-forward - i open a command prompt window and type 'soulseek login', then a prompt requests username, after i type in and press enter i'm requested a password.
so far, i manage to get the prompt of the username but not getting passed that.
subprocess.run('soulseek login',shell=True)
this results in the ?Login output in the python console but also the process is stuck, when i run in debug or also in run
is there a better way to go about this?
Interacting continuously with a system via subprocess can be tricky. However, it seems that your interface prompts are one after the other, which can therefore be chained together, via newline characters which act as Return key strokes.
For example, the program shown below simply prompts a user for their username and a password, to which the 'user' (your script) provides the input via the proc.communicate() method. Once these are provided, the user is asked if they'd like to continue (and do the same thing again). The following subprocess call feeds the following input into the prompter.py script:
username
password
continue reply (y or n)
Example code:
import subprocess
uid = 'Bob'
pwd = 'MyPa$$w0rd'
reply = 'n'
with subprocess.Popen('./prompter.py',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
text=True) as proc:
stdout, stderr = proc.communicate(input='\n'.join([uid, pwd, reply]))
Output:
# Check output.
>>> print(stdout)
Please enter a username: Password: uid='Bob'
pwd='MyPa$$w0rd'
Have another go? [y|n]:
# Sanity check for errors.
>>> print(stderr)
''
Script:
For completeness, I've included the contents of the prompter.py script below.
#!/usr/bin/env python
from time import sleep
def prompter():
while True:
uid = input('\nPlease enter a username: ')
pwd = input('Password: ')
print(f'{uid=}\n{pwd=}')
sleep(2)
x = input('Have another go? [y|n]: ')
if x.lower() == 'n':
break
if __name__ == '__main__':
prompter()
I am trying to understand how to execute a command/program using python subprocess module & respond to the prompt by giving input.
Sample Program Program1.py which can take multiple input's:
arr1=[]
username = input("Enter your username1 : ")
password = input("Enter your password1 : ")
arr1.append((username,password))
username = input("Enter your username2 : ")
password = input("Enter your password2 : ")
arr1.append((username,password))
username = input("Enter your username3 : ")
password = input("Enter your password3 : ")
arr1.append((username,password))
username = input("Enter your username4 : ")
password = input("Enter your password4 : ")
arr1.append((username,password))
for item in arr1:
print("username:",item[0],"Password:",item[1])
I have written another program called Execute_Program1.py
import subprocess
proc = subprocess.Popen('python Program1.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
print(proc.poll())
while proc.poll() is None:
print(proc.stdout)
proc.stdin.write('inputdata\n')
But this program is not able to execute the Program1.py. I have read many posts related to this. As per the information I have got proc.poll() return's None then the command executed by Popen is still active.
But my program is giving the following output:
None
<_io.TextIOWrapper name=4 encoding='cp1252'>
I am using Python version 3.7.4. Could anyone please help me with some inputs where I am doing mistake?
Thanks in advance.
I could not get it to work with subprocess at this time but I wanted you to have an ASAP working solution using the os module in case you need this quickly and are not absolutely required to use the subprocess module...
First add this line to the end of Program1.py, with no indentation, to prevent the command window from exiting before you have a chance to see the output:
input("Press <enter> to continue")
Next, replace your entire code in Execute_Program1.py with the following:
import os
os.system("python Program1.py 1")
This worked beautifully in Python 3.8.1 on win10pro.
I have made a program which requires the user to go and come back after completing the command, I would like the user to press ENTER to then continue the programme, to do this I used a normal Input command that does not record the answer. However I would like it if the user cannot enter any text, the only thing they can do is press ENTER to proceed.
input("Please charge your device, when you are finished, press ENTER on the keyboard")
You can try to write an if loop that checks whatever the input is enter: For example:
import tty
import sys
import termios
orig_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin)
x = input("Text")
while x != chr(13): # Enter
x=sys.stdin.read(1)[0]
print("ERROR PLEASE TRY AGAIN")
x = input("Text")
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
You might like to check this answer by #Turn at the question here: https://stackoverflow.com/a/34497639/2080764
Essentially, i want what is in this thread: Output to console while preserving user input in ruby, but in Python. I have googled for quite a while, and found an ALMOST working solution, except that it blocked the main thread, as long as i wasn't typing anything in and pressing enter.
Some output of what i don't want to happen is here:
/raw:jtv!jtv#jtv.tmi.twitch.tv PRIVMSG #cobaltstreak :USERCOLOR ullr_son_of_sif #DAA520
Some example input of what i want is:
:jtv!jtv#jtv.tmi.twitch.tv PRIVMSG #cobaltstreak :USERCOLOR ullr_son_of_sif #DAA520
/raw
PRIV:jtv!jtv#jtv.tmi.twitch.tv PRIVMSG #cobaltstreak :SPECIALUSER nightbot subscriber
MSG #cobaltstreak :This shouldn't be here, but on the same line with /raw
This meaning, i want the bottom line of the console to preserve input, while outputting everything happening in the main thread without affecting input.
My current code is:
def console(q, m, lock):
while 1:
raw_input() # After pressing Enter you'll be in "input mode"
with lock:
i = raw_input('> ')
cmd = i.split(' ')[0]
msg = i.strip(cmd + ' ')
q.put(cmd)
m.put(msg)
if cmd == 'quit':
break
as well has:
cmd = cmd_queue.get()
msg = msg_queue.get()
action = cmd_actions.get(cmd)
if action is not None:
action(stdout_lock, msg)
Note the code above is the very first couple of lines in my while loop.
I am on Windows and using python 2.7.6
I am using python 2.7.6, and when calling raw_input(), there is an exception:
flight_name = raw_input('\nEnter the name of Flight: ')
I found the solution, but why there appears such exception? Is it a bag?
try:
flight_name = raw_input('\nEnter the name of Flight: ')
except (EOFError):
break
You could use:
sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')
source: https://stackoverflow.com/a/7437724/1465640
This answer
sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')
is useful if you've previously read from sys.stdin in your code. In that case, the raw_input line will throw the EOF error without waiting for user input, if you set the sys.stdin = open('/dev/tty') just before raw_input, it resets the stdin and allows the user input to work. (tested in python 2.7) with
## test.py
import sys
for line in sys.stdin:
pass
#sys.stdin = open('/dev/tty')
raw_input("Are you sure?")
echo 'abc' | python test.py
Which raises:
EOFError: EOF when reading a line
Until you uncomment the 2nd to last line.
You're trying to read something from standard input but you're not getting anything, only the EOF. This actually lets you know the user is not providing any input and you can do other things for this condition.