I know that it is an easy question but I can't do this. I have to do two things. One of them is a management program that will manage the program, e.g stop, pause, resume. The other thing will only show logs. So I need 2 consoles.
How can I open two consoles?
How to pass a log from management console to logging console. Example code is below:
if __name__ == '__main__':
try:
while True:
initialmyProgram()
print('Please press \'1\' key to stop program..\n')
print('Please press \'5\' key to resume program..\n')
print('Please press \'0\' key to exit program..\n')
isStart = raw_input('Please press a key that must be in above list..')
if isStart == 1:
parse.__is__process__ = False
elif isStart == 5:
parse.__is__process__ = True
elif isStart == 0 :
exit_program()
else:
continue
except Exception as ex:
logging.info('log..') #this log will write other console..
You don't really need two python consoles to accomplish this.
If you're using linux or a mac, open up a python console and a second terminal.
Then type this command in the second terminal:
tail -f path_to/filename_of_logfile
This will refresh the log file automatically.
An alternative solution if you absolutely cannot use files, is to use sockets to have to python programs communicate. Here's a link to get you started:
Python Sockets
Related
Code :
from sys import exit
didlogcorrect = 1
Minecraft = 'Minecraft'
Roblox = 'Roblox'
Exit = 'Exit'
chrome = 'chrome'
print('Welcome To PotatOS')
user_input = input("What would you like to do on PotatOS: ")
if user_input == Roblox:
print('Unable to connect to wifi Now terminating process')
elif user_input == Exit:
exit()
elif user_input == chrome:
print('You open Chrome Thinking What should i do now Maybe youtube idk, Then you close Chrome cause your bored!')
elif user_input == Minecraft:
print('Crashed, Reason 1, you close it cause your mad it crashed')
else:
print('PotatOS : BEEERGZ Unable to understand')
crash :
Welcome To PotatOS
What would you like to do on PotatOS: Minecraft
Traceback (most recent call last):
File "/home/Username/Coding/PotatOS-1.0.1.txt", line 27, in <module>
if user_input == Roblox:
NameError: name 'Roblox' is not defined
Please help I would like someone with python knowledge to look at this I still cant find out why this wont work =(
I tried Multiple things but it still crashed, Sadly.
Thanks for being here and reading if you can help please let me know or help
Functionalities:
The built-in input function writes a prompt to standard output without a trailing newline and then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you want to compare values, you need to check the user input like this using if/elif/else statement. Make sure they are on the same indentation level, as python doesn't use braces to distinguish code blocks. See PEP8 for more information about indentation guidelines.
from sys import exit
didlogcorrect = 1
Minecraft = 'Minecraft'
Roblox = 'Roblox'
Exit = 'Exit'
chrome = 'chrome'
print('Welcome To PotatOS')
user_input = input("What would you like to do on PotatOS: ")
if user_input == Roblox:
print('Unable to connect to wifi Now terminating process')
elif user_input == Exit:
exit()
elif user_input == chrome:
print('You open Chrome Thinking What should i do now Maybe youtube idk, Then you close Chrome cause your bored!')
elif user_input == Minecraft:
print('Crashed, Reason 1, you close it cause your mad it crashed')
else:
print('PotatOS : BEEERGZ Unable to understand')
This error is coming because you're trying to map 4 values (chrome, Roblox, Exit, and Minecraft) while giving only one value from input().
If you want to put 4 different values in one input with space and be mapped into each variables,
e.g.
>>> What would you like to do on PotatOS
>>> Here,Type,Your,Answer
--
result:
chrome -> 'Here'
Roblox -> 'Types'
Exit -> 'Your'
Minecraft -> 'Answer'
You can try adding .split() followed by input()
So your code might look like this.
Try to remove the split count value first, and make sure you're doing right in typing in input values.
chrome, Roblox, Exit, Minecraft = input("What would you like to do on PotatOS").split(",")
I suggest doing
user_input = input("What would you like to do on PotatOS")
Then doing something with user_input. The key here is to keep each line of code as simple as possible. As you learn more about python, you will discover when it is appropriate to chain two method calls together, but until then, don't.
I'm really only using it for command history up/down functionality on windows - I couldn't get pyreadline3 to work correctly. Everything works fine, but using the up and down keys creates up to 40 threads that never go away.
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
while True:
print("\n")
print("=============")
print("Enter command")
command_text = prompt('>', history=FileHistory('command_history.txt'),)
cmd = command_text.lower().strip()
if cmd == "": # skip empty input
continue
if cmd == "exit": # bail
break
process_command(cmd)
That's basically it. Is this normal behavior? I guess the threadpool just creates new threads up to its maximum, but it seems a little excessive for this task, and makes my VScode call stack a mess.
I am using python3.7
I wrote a script which takes some inputs (e.g. a=input("enter a value")
it runs smoothly if i go to its path and run it on command prompt.
I can give input also and run .
If i give wrong input it shows an error or exception(traceback)
So i converted it to .exe using pyinstaller
when i run .exe , it asks for input as expected ,it runs and vanishes , i can't see any output.
if i give a wrong input it suddenly vanishes without showing any traceback
I read many questions regarding this on stackoverflow and google , so i added an input statement at end to make program wait before exiting,
but it doesn't works in case of wrong input or if i use sys.exit("test failed") in some cases it just vanishes ,how to resolve and keep cmd window open?
Adding script for e.g.:
import sys
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
if x>100 or y > 100 :
sys.exit("ERROR :value out of range")
z=x+y;
print(z)
input('press enter to exit')
if inputs are less than 100 and integer then script(.exe file) runs smoothly and i get message "press enter to exit"
but if input number greater than 100 or if i put a "string or float" in input , cmd window vanishes without display any traceback
whereas if i run py file from cmd then i get proper traceback for wrong input.
You could use try-except and input() function, so that when there is any error, it will wait for the user to interact.
Look at this example -
a = input('Please enter a number: ')
try:
int(a) # Converts into a integer type
except ValueError as v:
# This will run when it cannot be converted or if there is any error
print(v) # Shows the error
input() # Waits for user input before closing
For your e.g code, try this -
import sys
try:
x = int(input(" enter a number :"))
y = int(input(" enter a number :"))
except ValueError as v:
print(v)
input('Press any key to exit ')
sys.exit()
if x>100 or y > 100 :
try:
sys.exit("ERROR :value out of range")
except SystemExit as s:
print(s)
input('Press any key to exit ')
sys.exit()
z=x+y
print(z)
You will see that the command prompt does not close immediately
You're not waiting for input.
When you run a .exe that's set up to run in the Windows console, unless you've already opened the console and if your program through that using console commands, and it was set up to just run all the way through to the end, you'll just see the window pop up and then close itself unless your program is doing something that requires user input or a lot of computational time.
This is fairly common sight when programming with languages like C# that natively run as .exes; presumably, this behaviour would also be fairly common in Python. The way to fix this is to add in a line at the end of your program to ask the user for input, so that the console will wait for the user before closing.
In your case, you mention that you have added to the end of your program; the problem is that the program isn't getting to that stage because it's hitting an exception and then exiting. You'll need to handle your exceptions and add a prompt for user input to prevent this behaviour.
Use while loop so if you gave wrong input then it will return to input again so you can give any input. and for example if you want to use only integer value then input must be convert as integer or string depend on you. example below now I think you can
ask = "" #ask variable empty here because I want to use in while condition
print("YOU LOVE ME")
while ask != 'Ok Son':
ask = input("Why? : ")
print("OK THANKS DAD")
I've been trying to find a way to take a user input that ends in the user pressing Tab. What I want to happen is for the user to type notes and it doesn't finish the input until they press Tab.
I was trying to use this method but not sure what to do.
text = input()
I want the user to type notes and be able to go to a new line by pressing Enter without finishing the input. Only if the user presses Tab will the input finish and the text get stored into the variable.
What you're asking for sounds straightforward, but unfortunately isn't very easy to do. The problem is that input from the command line to your program is line-buffered. That is, it only gets sent to the program one line at a time. There are some difficult ways to get around this, but they generally don't work very well.
If you clarify your question with what you are trying accomplish one level above this, people might be able to offer an even better solution. In the meantime, here's a simple version that ends the input if the user presses tab then enter:
def get_input_ending_with_tab():
inp = input() + "\n"
while not inp.endswith("\t\n"):
inp += input() + "\n"
return inp
And here's a more complicated version that does what you want, but will not work on Windows. This will also only work in an interactive execution of your program (when it's attached to a TTY).
import sys
import tty
import termios
def get_input_ending_with_tab_2():
buf = ""
stdin = sys.stdin.fileno()
tattr = termios.tcgetattr(stdin)
try:
tty.setcbreak(stdin, termios.TCSANOW)
while True:
buf += sys.stdin.read(1)
print(buf[-1], end="")
sys.stdout.flush()
if buf[-1] == "\t":
break
finally:
termios.tcsetattr(stdin, termios.TCSANOW, tattr)
print()
return buf
Good Afternoon,
I used a version of this method to map a dozen drive letters:
# Drive letter: M
# Shared drive path: \\shared\folder
# Username: user123
# Password: password
import subprocess
# Disconnect anything on M
subprocess.call(r'net use * /del', shell=True)
# Connect to shared drive, use drive letter M
subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True)
The above code works great as long as I do not have a folder with a file in use by a program.
If I run the same command just in a cmd window and a file is in use when I try to disconnect the drive it returns the Are you sure? Y/N.
How can I pass this question back to the user via the Py script (or if nothing else, force the disconnect so that the code can continue to run?
To force disconnecting try it with /yes like so
subprocess.call(r'net use * /del /yes', shell=True)
In order to 'redirect' the question to the user you have (at least) 2 possible approaches:
Read and write to the standard input / output stream of the sub process
Work with exit codes and start the sub process a second time if necessary
The first approach is very fragile as you have to read the standard output and interpret it which is specific to your current locale as well as answering later the question which is also specific to your current locale (e.g. confirming would be done with 'Y' in English but with 'J' in German etc.)
The second approach is more stable as it relies on more or less static return codes. I did a quick test and in case of cancelling the question the return code is 2; in case of success of course just 0. So with the following code you should be able to handle the question and act on user input:
import subprocess
exitcode = subprocess.call(r'net use * /del /no', shell=True)
if exitcode == 2:
choice = input("Probably something bad happens ... still continue? (Y/N)")
if choice == "Y":
subprocess.call(r'net use * /del /yes', shell=True)
else:
print("Cancelled")
else:
print("Worked on first try")