This code stopped doing anything at all after I changed something that I no longer remember
#Dash Shell
import os
import datetime
class LocalComputer:
pass
def InitInformation():
Home = LocalComputer()
#Acquires user information
if (os.name == "nt"):
Home.ComputerName = os.getenv("COMPUTERNAME")
Home.Username = os.getenv("USERNAME")
Home.Homedir = os.getenv("HOMEPATH")
else:
Home.ComputerName = os.getenv()
Home.Username = os.getenv("USER")
Home.Homedir = os.getenv("HOME")
return Home
def MainShellLoop():
print ("--- Dash Shell ---")
Home = InitInformation()
userinput = None
currentdir = Home.Homedir
while (userinput != "exit"):
rightnow = datetime.datetime.now()
try:
userinput = input(str(Home.ComputerName) + "\\" + str(Home.Username) + ":" + str(rightnow.month) + "/" + str(rightnow.day) + "/" + str(rightnow.year) + "#" + str(currentdir))
except:
print("Invalid Command specified, please try again")
MainShellLoop()
edit: Lol sorry guys forgot to say its supposed to run the input
You should better describe your problem. Does it print the input prompt? Does it output anything? Does it exit or just sit there? I noticed a few issues while reading over this code that might help. You should be using raw_input(), not input(). Also, you don't actually do anything with userinput unless it == 'exit'. Which is won't, because you are just using input(), not raw_input(), so the person would have to enter 'exit' (including quotes) or else the loop will never exit. (Assuming it's not Python 3 Code)
It's doing nothing because there's no code to make it do anything. Try inserting a line like
print("You entered:", userinput)
at an appropriate place in your loop.
os.getenv() must have at least one param. Try os.getenv("HOST") or something.
Related
So I made a very simple Auto-typer and want to be able to run it again or quit it.
All works perfectly fine but at the end the "ending = input()" doesnt let me type it just exits out of the programm. Any reason why?
import pyautogui
import time
import os
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
break_loop = 1
while break_loop <= 1:
secs_inbetween_actions = float(input("""
Seconds between actions(should be float but int is also ok): """))
no_of_lines = int(input("""
How many Lines do you want to write?(Only int): """))
time_between_action = int(input("""
How long should the time between enter and writing be?: """))
lines = ""
print("""
Write your Text under this message (You have """ + str(no_of_lines) + """ line(s) to wite)
""")
for i in range(no_of_lines):
lines += input() + "\n"
print("-------------------------------------")
while time_between_action > 0:
time_between_action = time_between_action - 1
print('Time Left until writing -+==> ' + str(time_between_action))
time.sleep(1)
print("-------------------------------------")
pyautogui.typewrite(lines, interval=secs_inbetween_actions)
ending = input("If you want to use this aplication once again type 'y' + 'enter key' ,if not press the 'enter key': ")
if ending == "y":
break_loop = 1
clearConsole()
else:
break_loop += 1
This is a rather fun little problem. It occurs, as #Barmar notes, because pyautogui.typewrite() is writing to the console for you. I incorrectly thought that it was not happening when there was no delay between actions, which was a far more puzzling little problem.
In this case the solution is easy: add after your typewrite():
if lines:
input()
To absorb what has just been typed for you.
This question already has answers here:
How to stop the input function from inserting a new line?
(9 answers)
Closed 4 years ago.
Is it possible to remove the prompt and the text that the user typed when using input()? I am using cmd on Windows 10 and would prefer a solution that works cross platform, but I don't really mind.
First attempt
Using the code:
user_input = input("Enter some text: ")
print("You just entered " + user_input)
produces:
Enter some text: hello
You just entered hello
but I would like:
Enter some text: hello
and then:
You just entered hello
Second attempt
I've used the getpass module, but that hides what the user is typing because it is designed for passwords. I looked at the code for getpass2 here and found that it uses the getch() function from msvcrt. I tried using a similar method, but it did not work. This code:
import msvcrt
prompt = "Enter some text: "
user_input = ""
print(prompt, end="\r")
current_character = ""
while current_character != "\r":
current_character = msvcrt.getch()
user_input += str(current_character, "utf8")
print(prompt + user_input, end="\r")
print("You entered" + user_input)
produces this output:
Enter some text: h e l l o
and then when I press enter:
nter some text: h e l l o
It also allows the user to use the backspace key to delete the prompt.
Third attempt
I know I can use os.system("cls") to clear everything in the console, but this removes text that was in the console before. For example, this code:
import os
print("foo")
user_input = input("Enter some text: ")
os.system("cls")
print("You just entered " + user_input)
removes the foo that was printed to the console before the input. If what I'm asking isn't directly possible, is there a workaround that can save the text in the console to a variable, and then after the user input clear the console and reprint the text that was in the console?
This is definitely not the optimal solution;
However, in response to
is there a workaround that can save the text in the console to a
variable
, you could keep appending the required text to a variable, and re-print that each time, as you suggested. Again, I would not recommend this as your actual implementation, but while we wait for someone to come along with the correct approach...
import os
to_print = ""
to_print += "foo" + "\n"
print(to_print)
user_input = input("Enter some text: ")
os.system("cls")
to_print += "You just entered " + user_input + "\n"
print(to_print)
I've worked with little personal assistant project lately and now I'm facing this problem/bug and I can't get over it.
Here's part of my code:
import os
import sys
from colorama import Fore, Back, Style
import random
from os import system
from src import commands
system("title Assistant")
actions = {
"open":["pubg", "dota", "origins", "spotify", "dogs"],#"open":{["o"]:["pubg", "dota", "origins", "spotify", "dogs"]},
"hue":["1"],
"clear":"",
"hiber":"",
"shutdown":""
}
class MainClass:
#
logo1 = Fore.CYAN + """Not essential"""
logo2 = Fore.CYAN + """Not essential"""
errorcode = "Something went wrong :("
def getCommand(self):
cmd = input(Fore.MAGENTA + "Assistant > " + Fore.CYAN)
print("cmd: " + cmd)
self.checkCommand(cmd)
def checkCommand(self, cmd):
actions = commands.Commands().actions
words = cmd.lower().split()
print("Words: " + ' '.join(words))
found = False
ekasana = ""
par = ""
print("running if " + words[0] + str(words[0] == "q"))
#Here's the problem. After I imput 'clear', which clear's the screen and runs mainInterface(2.0, randomthing), this if does not work.
# Here's the output
# Not essentialv 2.0
# By Dudecorn
# Assistant > q
# cmd: q
# Words: q
# running if qTrue
# self.errorcode
# clear
# ['clear']
# Assistant >
# Why is is that clear command staying there? I am so confused right now.
# Read line 68
if words[0] == "q":
quit()
sys.exit()
for word in words:
word = ''.join(word)# Sorry about the mess
print(word)
# Check for action without parameters
if word in actions and actions[word] == "" and found == False:
try: # I'm pretty sure that this part of code is causing the problem
# If you remove try and except, and leave just lines 70 and 71, code works as line 58 if statement's value is true.
# This is in the another file -> getattr(commands.Commands, word)(self)
self.mainInterface(2.0, random.randint(1, 2))
break
except:
print("self.errorcode")
print(word)
print(words)
# Check for action that has parameters
elif word in actions and not actions[word] == "" and found == False:
ekasana = word
found = True
# Check for parameters
elif not ekasana == "" and found == True:
for n in actions[ekasana]:
if n == word:
par = word
try:
getattr(commands.Commands, ekasana)(self, par)
except:
print(self.errorcode)
else:
print("Command not found")
self.getCommand()
def mainInterface(self, v, logo):
os.system('cls' if os.name == 'nt' else 'clear')
if logo == 1:
print(self.logo1+"v "+str(v)+"\n By Dudecorn")
else:
print(self.logo2+"v "+str(v)+"\n By Dudecorn")
self.getCommand()
And here's the main file
import test
import random
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
So, when you run the code and first input 'clear' and then q the if statement won't execute. And I wonder why. I also noticed that if you remove try and except from first if statement after loop the code works perfectly. I could remove them but it wouldn't answer my question, why isn't the code working. Also removing try and except from the file should not have any effect on how the first if statement executes, as it comes up later in the code.
Sorry about bad english as it isn't my main language, and thank you for your answers. Also I want to apologize for that huge mess in the code.
I am not sure if this is the answer that you are looking for, but it may be useful to check.
From the code below,
def main():
m = test.MainClass()
m.mainInterface(2.0, random.randint(1,2))
main()
, I see that by running main(), you also run the m.mainInterface function.
Now..you may want to check this :
The method mainInterface will eventually call the method getCommand, which will eventually call checkCommand, which..will encounter the try block in the for word in actions loop, and inside this try block..there is a calling of mainInterface again..so this process will be keep repeating.
Hello please forgive me if my question duplicate, I've searched previous questions and nothing seems to be quite the same. I'm working on a program that will scan a specific folder and search for specific file types to create a menu for a user to select. Once the user select the menu option the the corresponding file which is a power shell script. Currently My program does everything but run even a simple power shell script. I've attempted several configuration and it's not working. It would be great if someone can see what I may be doing wrong or provide me with some pointers. Code below.
##Text Menu Dynamic test
##version 1
## Created By Dragonshadow
## Code produce in Notpad++ For python v3.4.4
import os
import subprocess
import time
import pathlib
import logging
import fnmatch
import re
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir('C:\\Users\\myfolder\\Documents\\Automation_Scripts\\ENScripts\\'),"*.ps1")
selectedFile=""
## Menu defined setting veriables
def ENOC_menu():
files = fileFolderLocationFilter
counter = 1
print (20 * "=" , "Enoc Quick Menu" , 20 * "=")
enumFiles = list(enumerate(files))
for counter, value in enumFiles:
str = repr(counter) + ") " + repr(value);
print(str)
str = repr(counter+1) + ") Exit";
print(str)
print (57 * "_")
str = "Enter your choice [1 - " + repr((counter+1)) + "]:"
choice = int(input("Please Enter a Selection: "))
selectedFiles = enumFiles[choice]
return(selectedFiles[1])
if choice > counter :
choice = -1
elif choice != counter :
print("Please selecte a valid choice")
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
##selectedFiles = selectedFiles[1]
return choice
def you_sure():
opt = input("Are you sure Yes or No: ")
if opt=="Yes":
print("Continuing please wait this may take a moment...")
elif opt=="No":
print("returnig to Enoc Menu")
else: ##Stays in loop
print ("Please choose yes or no")
##count_down
def count_down ():
count_down = 10
while (count_down >= 0):
print(count_down)
count_down -= 1
if count_down == 0:
print("Task will continue")
break
##initiating loop
loop = True
while loop:
choice = ENOC_menu()
print ("\n" +"You selected "+ choice +"\n")
subprocess.call("C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe" + choice, shell=True)
##print ("---" +str(selectedFile))
You have probably already figured this out, but I the problem is in the subprocess.call() line. You are concatenating the powershell.exe path and the target file name together. See here:
>>> scriptToRun = "c:\\users\\Username\\Documents\\WindowsPowerShell\\classtestscript.ps1"
>>> powershellExe = "c:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe"
>>> print(powershellExe + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exec:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
Above, the two strings are stuck together without a space between them. Windows can't make sense of what you're trying to execute.
Put a space between the two two and subprocess.call() will understand what you're trying to do:
>>> print(powershellExe + ' ' + scriptToRun)
c:\windows\system32\windowspowershell\v1.0\powershell.exe c:\users\Username\Documents\WindowsPowerShell\classtestscript.ps1
import os
name = input("Please enter your username ") or "name"
server = input("Please enter a name you wish to call this server ") or "server"
prompt = name + "#" + server
def error(choice):
print(choice + ": command not found")
commands()
def clear():
os.system("cls")
commands()
def commands():
while 1 > 0:
choice = input(prompt)
{'clear': clear}.get(choice, error(choice))()
commands()
When running this code, no matter what I enter the dictionaries .get function always returns an error. When I enter 'clear' the script should go to that function. Does anyone have an idea why this does not work correctly? Thanks.
You'll always see the error, because all arguments to a function must be evaluated before the function is called. So error(choice) will be called to get its result before it is passed as the default value to get().
Instead, leave out the default, and check it explicitly:
result = {'clear': clear}.get(choice)
if result:
result()
else:
error(choice)
You don't want to actually call error(choice).
You can partially apply parameters to a function but leave it to be called later:
>>> def error(choice):
... print(choice + ': command not found')
>>> from functools import partial
>>> func = partial(error, choice='asdf')
>>> func()
asdf: command not found
So you want:
{'clear': clear}.get(choice, partial(error, choice))()