I click enter to enter input data and it closes.
I am using windows ten, new computer, not glitchy.
code is
import os
printput = input("Do: ")
if printput == "send message":
myinput = input("s:")
print (myinput)
pass
elif printput == "clear term":
os.system("clear")
pass
what I do, "Do: send message, Enter, s:random stuff, Enter, #window closes#"
I don't know how you are running your file, but probably at the end of the execution the terminal is closing automatically, to avoid that you can open the windows terminal, navigate to where your file is stored using cd for example cd Desktop and then start your file using the command python filename.py that way the terminal won't close even after your file finishes executing. A better solution that will help you in developing what seems to be a shell that executes your commands is using a while True: at the beginning. This way no matter how you execute your file, terminal won't close. and your script will keep running your commands until you close it, And your code will become like this :
import os
while True:
printput = input("Do: ")
if printput == "send message":
myinput = input("s:")
print (myinput)
pass
elif printput == "clear term":
os.system("cls")
pass
this way your code will keep running forever and asking you for commands and executing them, and i changed os.system("clear") because it doesn't work, to os.system("cls") the command that clears the terminal.
another thing you can do to avoid terminal from closing at the end of execution is to make it wait for a keypress by adding at the end of your code
input("Press Enter to continue...")
Related
I'm making a sort of quick launch app for things I'm making. However, when I try to launch something, I can't launch another thing until the first thing is done running. For example:
command = input(">>> ")
if command == "launch music" :
exec(open("music.py").read())
command = input(">>> ")
As you can see, the code after the exec() function does not run until after the file has stopped. How can I make it so that the file runs separately from my main code?
I am a complete beginner in python as well as this website.
Background:
I have tried to program a random password generator that allows the user to input the length of the password and how many passwords the user wants.
Everything works perfectly fine when I run the program in pharm. So I converted the script into .exe file. It does not crash instantly, it stills allow the user to input values but once the user entered the values in, it crashes.
I tried using pyinstaller from youtube tutorials to "properly" convert the script into .exe, but the same result still occurs. (Previously, I simply copy and paste my script into notepad and name that notepad in terms of .py and run it.)
Here are my codes:
import random
import sys
chars = "abcdefghijklnmopqrstuvwxyzABCDEFGHIJKLNMOPQRSTUVWXYZ0123456789!##$%^&*+="
try:
length_password = int(input("Enter the length of your password: "))
how_many = int(input("Enter how many passwords you want: "))
except:
print("Invalid input (numbers only!)")
sys.exit()
def length_function(length):
password = ""
for number_times in range(0, length_password):
password = password + random.choice(chars)
return password
print("Here are your passwords: ")
number_times1 = 1
while number_times1 <= how_many:
print(length_function(length_password))
number_times1 = number_times1 + 1
Like I mentioned before, it runs well in pycharm but not in a .exe file.
I've seen your other question and try to explain more on the solution for this problem:
When running a code, program, or whatever, that code might end somewhere, where nothing has to be done anymore.
That's the point where your operating system (Windows, Linux etc) just exits the program. What you might expect is that the console stays open so you can read the ouput, right?
So why does this often work but often doesn't?
When calling your code from an already existing command window (for e.g. cmd.exe), the console (which is a program itself) is not finished and won't close after runnning your program. That's the point where you can read the printed output from you own program.
When you call your program from somewhere else, it is opening a console just for that purpose and it's configured in that way, that it doesn't stay open after executing your program. So when your code is executed, it prints something on the console; but immediately after its done and the console closes, too.
That is where the solution input("Press Enter to exit") comes into play. input() is a function which waits for user input; so it's waiting infinitely for you to hit enter. That means, your program is not finished. That gives you the time you read the output you want to read.
CMD writes this when I run command "vsc" which open VSCode
This is the function i made to open VSCode
def openVSC():
subprocess.call(["C:\\Program Files\\Microsoft VS Code\\Code.exe"])
And this is the code that calls the function "openVSC()"
while True:
command_input = input(prompt).lower()
if command_input == "open spotify":
print("Opening Spotify...")
openSpotify()
print()
elif command_input == "www":
print("Opening Google Chrome...")
openChrome()
print()
elif command_input == "vsc":
print("Opening VSCode...")
openVSC()
print()
elif command_input == "quit":
break
else:
pass
Also when I close the cmd VSCode also closes so I was thinking that the CMD was running VSCode on his own... Nothing seems to work and i tried about everything.
Your question is very vague, more information would be appreciated. Assuming you issue is that you are only getting STDOUT from the vscode call, thats because you are using call(), which waits for the process to complete before returning control to your program. Use something like this to make your call, and you can set where STDOUT points to as to read output whilst using the program being called by your script.
from subprocess import Popen, STDOUT
import os
Popen(['vscode'], stdout=os.open(os.devnull, os.O_RDWR), stderr=STDOUT)
This will open the process to run as a child and your program will wait for the child to terminate at this point. Read more into subprocess and this should all make more sense. hope this helps!
First of all let me say sorry that I was unable to condense this problem any further. It's a very simple concept but I found it very difficult to word in a way that could be universally understood. Many of the words I use below get tossed around so carelessly you have to set up a whole scenario to use them intelligibly.
I'm running a game script in interactive mode so that if I break it with an exception I can still interact with the game environment (classes, objects and variables).
myScript.py:
def game():
print("")
print("Starting game loop...")
display=0
while True:
print(display)
command = input("Press ENTER to proceed...")
game()
But every time I update the script I have to break the loop with break by specifying 'console' at the user prompt, and then call exit() at the console before returning to the terminal where I can then run the script fresh.
So I added these lines to the game loop:
if command.lower() == "console":
print("")
break
elif command.lower() == "terminal"
#exit() throws an exception
#`import sys` nl `sys.exit()` throws an exception
else:
display+=1
print("")
print("Continuing game loop...")
Output:
user#user-VirtualBox-Ubuntu:~$ python3 -i /home/username/scripts/myScript.py
Starting game loop...
0
Press ENTER to proceed, enter 'console' to halt and 'terminal' to leave...
Continuing game loop...
1
Press ENTER to proceed, enter 'console' to halt and 'terminal' to leave...
Continuing game loop...
2
Press ENTER to proceed, enter 'console' to halt and 'terminal' to leave...
Continuing game loop...
3
Press ENTER to proceed, enter 'console' to halt and 'terminal' to leave... console
>>>
As you can see above, I have prepared an elif circumstance for skipping a step and going straight to the terminal, where I should then be able to press UP twice to find clear and then UP twice again to find my interactive script call line. But, the only relevant solution I could find on SO is the one you can see in my myScript.py file involving the import of sys, which throws an error.
So, is it possible to produce the behavior of exit() (when typed from the command line) from a script without generating exceptions?
I found this code snippet online for a python terminal emulator, I thought it looked cool so I went ahead and attempted to use it. I noticed that I'm not able to use the "cd" command, I'm stuck in the directory I ran the file in. Why is this? What's going on? And how can I modify this code to make it run like a perfect native terminal? I'm still very new to programming and have only played with the subprocess module once in my life. Please help!
import subprocess
import re
while True:
# prevents lots of python error output
try:
s = raw_input('> ')
except:
break
# check if you should exit
if s.strip().lower() == 'exit':
break
# try to run command
try:
cmd = subprocess.Popen(re.split(r'\s+', s), stdout=subprocess.PIPE)
cmd_out = cmd.stdout.read()
# Process output
print cmd_out
except OSError:
print 'Invalid command'
When you open a new process you change the current directory for the new process and not for the calling process. You should use os.chdir instead to change the directory of your program. So you need to parse the command line and check if the command is cd and then decide not to call Popen but os.chdir instead.