Removing input() text from console Python3 - python

I want to clear the line of text created after the input() function. I've tried \033[a, \r, end='' but either I'm doing it wrong or it doesn't work. Is there a better way:
Code is:
rawguess = input('Enter a 5 letter word: ')
print('words go here')
I've tried:
rawguess = input('\033[A' + 'Enter a 5 letter word: ' + '\033[A')
print('words go here')
rawguess = input('Enter a 5 letter word: ')
print('\rwords go here')
rawguess = input('Enter a 5 letter word: ')
print('\r', end='')
print('words go here')
And other variations of these three but nothing's worked so far.

I didn't know this before, but apparently Windows now supports Console Virtual Terminal Sequences, which include using ESC [ <n> A to move the cursor up (like on *nix). So we can call the Win32 API with ctypes.windll and enable Virtual Terminal Sequences, which will allow us to use '\x1b[1A'.
import sys
# Only do this on Windows, so that *nix users
# can also run the program without errors
if sys.platform.startswith('win'):
import ctypes
from ctypes.wintypes import *
STD_OUTPUT_HANDLE = -11
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4
kernel32 = ctypes.windll.kernel32
h = kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
m = DWORD()
kernel32.GetConsoleMode(h, ctypes.pointer(m))
m.value |= ENABLE_VIRTUAL_TERMINAL_PROCESSING
kernel32.SetConsoleMode(h, m)
rawguess = input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here')

Well I just found a piece of dark magic allowing you to enable terminal controls in Python:
import subprocess
subprocess.run("", shell=True)
input('Enter a 5 letter word: ')
print('\x1b[1A' + 'words go here ')

Related

I cannot delete a file with python

First off I am not too familiar with python and still currently learning also its my first time ever posting here so sorry if I am mess up with some details.
I am running experiments, and need to run multiple replicates. The issue arises when I need to start a new set of replicates, the program moves the already run experiments into a new folder and is then suppose to start the new replicates. However, what happens only on the last experiment, the environment.cfg folder is not transferred and the program crashes.
from os import listdir,chdir
import subprocess
from random import randrange,sample
from shutil import copy,copytree,rmtree
from os import mkdir,remove
import csv
import time
import shutil
test = input("Is this a test? (y/n)")
if test == "y":
text = input("What are you testing?")
testdoc=open("Testing Documentation.txt","a")
testdoc.write(text)
elif test != "y" and test != "n":
print("Please type in y or n")
test = input("Is this a test? (y/n)")
expnum = int(input("Number of Experiments: "))
exptype = int(input("Which experiment do you want to run? (1/2)"))
repnum= int(input("How many replicates do you want?"))
print(f"You want {repnum} replicates, each replicate will contain {expnum} for a total of {repnum*expnum}")
confirm = input("Is this correct? (y/n)")
if confirm == "y":
for rep in range(repnum):
if exptype == 1:
for ex in range (expnum):
num= ex + 1
mkdir('experiment_'+str(num)) #create a directory named cdir
copy('./default_files/environment.cfg','./experiment_'+str(num)+'/environment.cfg') #copy one file from one place to another
#WSIZE
env_file = open('./experiment_'+str(num)+'/environment.cfg','r')
env_file_content = []
for i in env_file:
env_file_content.append(i.split(' '))
#env_file_content = [['a','b'],['c','d']]
#access first line: env_file_content[0] ; note that index in python start from 0
#access first element in second line: env_file_content[1][0] ; note that index in python start from 0
n = num #number of resources
var0 = '100' #resource inflow
var1 = '0.01' #resource outflow
var3 = '1' # The minimum amount of resource required
reactiontype = ['not','nand','and','orn','or','andn','nor','xor','equ']
reward = ["1.0","1.0","2.0","2.0","4.0","4.0","8.0","8.0","16.0"]
#n = sample(range(10),1)[0]
out = open('./experiment_'+str(num)+'/environment.cfg','w')
for i in range(n):
out.write('RESOURCE res'+str(i)+':inflow='+var0+':outflow='+var1+'\n')
sc=0
for i in range(n):
out.write('REACTION reaction'+str(i)+' '+reactiontype[sc]+' process:resource=res'+str(i)+':value='+reward[sc]+':min='+var3+ '\n')
sc+=1
if sc==len(reactiontype):
sc = 0
out.close()
##RUN Avida from python
copy('./experiment_' + str(num) + '/environment.cfg', './')
print("starting experiment_" + str(num))
proc = subprocess.Popen(['./avida'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Wait for the subprocess to finish
output, error = proc.communicate()
# Close the subprocess
proc.terminate()
shutil.move('./data','./experiment_' +str(num))
#copytree('./data', './experiment_' + str(num) + '/data')
#rmtree('./data')
remove('./environment.cfg')
replicatenum = rep + 1
mkdir('replicate_'+str(replicatenum)) #create a directory named replicate_
for repl in range(expnum):
numb = repl + 1
source = './experiment_'+str(numb)
dest = './replicate_' + str(replicatenum) + '/experiment_' + str(numb)
shutil.move(source, dest)
I tried renaming the folder, however that also failed. The issue seems only to arise when the program is running as taking the same code after the program has crashed, will cause no problems.

Why does Python say that I am giving 64 arguments for a function when I am only giving 1 each time with a for loop?

I'm making a dictionary attack with SHA-256 hashes from Violent Python and I have a function which tests the hash and sees if it matches the password. Then I have a main() function.
The program opens a dictionary file and a UNIX-style sheet with users and their hashes passwords.
I am using threads to test the words all at once, and using a for loop to test them:
from hashlib import *
from os import chdir
from pathlib import Path
from threading import Thread
from time import sleep
chdir(Path.home() / 'Downloads')
dict = open('dictionary.txt')
def test(encrypted):
for word in dict.readlines():
hash = sha256()
word = word.strip('\n')
hash.update(bytes(word))
if hash.hexdigest() == encrypted:
print('Match!:' + word)
else:
return null
def main():
users = open('users.txt')
for line in users.readlines():
user = line.split(':')[0]
encrypted = line.split(':')[1].strip(' ')
print('cracking for' + user + '...')
t = Thread(target = test, args = encrypted)
t.start()
main()
sleep(200)
Python gives me this error though:
TypeError: test() takes 1 positional argument but 64 were given
I think Python thinks I am trying to test all the dictionary words at once, but that is impossible because there are not 64 words in my dictionary, yet I can't find anything else wrong with the code.
apple
orange
egg
lemon
grapes
secret
strawberry
password
Here is the users.txt:
victim: 34707c3f40dfa20c3902b807b627d420d6d474d9d98066ba637953d1cfd6b914: 503:100:Iama Victim:/home/victim:/bin/sh
root: 3a7bd3e2360a3d29eea436fcfb7e44c735d117c42d1c1835420b6b9942dd4f1b: 504:100: Markus Hess:/root:/bin/bash
The args keyword of a Thread accepts a tuple
This might work :
t = Thread(target = test, args = (encrypted,))
Also there's nothing like null in python but none

pbcopy in Python to copy to the clipboard on OSX?

I am receiving the following error when trying to use pbcopy to add the output to the clipboard. I tried different variations of the command and still no luck.
Does anyone have any ideas where I may have failed?
Error Screenshot:
#!/usr/bin/env python3
# This script creates a secure password using all available key combinations.
import secrets , string, os
def prRed(skk): print("\033[91m {}\033[00m" .format(skk))
chars = string.ascii_letters+string.punctuation+string.digits # Cleaner way of assigning variable
print()
pwd_length = int(input('Enter the length of the desired password: '))
print()
print('[+] ' + 'Your secure password is:')
print()
for n in range(1):
output = ""
for i in range(pwd_length):
next_index = secrets.SystemRandom().randrange(len(chars))
output = output + chars[next_index]
prRed(os.system("echo '%s' | pbcopy" % output))
print()

Getting Python code to call a PowerShell script and run it

I could really use some help on this python script that is to call and run existing PowerShell scripts that are in a specific folder. From want I can see on from many of the articles on this site I've read my code seems correct. First a little background I'm trying to write a python script that will take Powershell scripts in a targeted folder and create a menu that can be selected 1, 2, 3 etc. The use makes the selection and that corresponding Powershell script is run. Now the issue is when I place the code on a server and run it with some test PowerShell scripts I get the following error: The term "Filename.ps1" is not recognized as the name of a cmdlet, function, script file, or operable program. And of course the Powershell scripts won't run. A copy of my code is below. Can anyone see any issue.
## ENOC Text Menu Dynamic test
##version 1
## Created By MTDL Marcus Dixon
## Code produce in Notpad++ For python v3.4.4
import os, subprocess, time, pathlib, logging, fnmatch,
re, sys, io
## Directory Enumerator
fileFolderLocationFilter = fnmatch.filter(os.listdir
('C:\\Users\\MTDl\\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
##initiating loop
loop = True
while loop:
try:
choice = ENOC_menu()
scriptToRun = choice
powershell = 'C:\\WINDOWS\\system32\
\WindowsPowerShell\\v1.0\\powershell.exe'
print ('\n' +'You selected '+ choice
+'\n')
subprocess.call(powershell + ' ' +
choice, shell=True)
except OSError as err:
logger.error(err) ##continue to work on
logging this renders but may be incorrect.
print ('OS error: {0}' .format(err))
except ValueError:
print ('Oops we had an issue try again')
else:
print ('---' + choice + '---' + '\n')

How to put text in input line: how to ask for user input on the command line while providing a 'default' answer that the user can edit or delete?

I am creating a Python script that asks for input from the command line. The user will have the ability to edit a part of a file. I can ask for the new information and overwrite it in the file, no problem. But I would rather have the to-edit part of the file already put in the command line, so it does not have to be typed completely over. Is this possible?
File:
1|This file
2|is not empty
Example:
>>>edit line 2
Fetching line 2
Edit the line then hit enter
>>>is not empty #This is written here by the script, not by the user
Which then can be changed to
>>>is not full either
Edited file
Afther which the file has changed to:
1|This file
2|is not full either
I hope it's clear what I am trying to accomplish.
This question has been said to answer my question, it does to a certain extent. It does when I am running Linux with readline. However, I am not. I am using Windows and am not using readline. I would like to only use the standard library.
An answer for Windows is also provided with that question. However, I get an ImportError with win32console, it might be because mentioned question is not about Python3.4, but mine is.
Also, I was wondering if this was possible with the standard library, not with an external library.
Unfortunately, I don't know if kind of input() with default value is available in standard library.
There is an external solution - use win32console as mentioned in this answer. However, it has two pitfalls as far as I can see. First, the import is bundled in a package pywin32. So you would use pip install pywin32, except it does not work, because of the second pitfall: the information about the package at pypi is outdated, it says that package is incompatible with Python 3.4...
But in fact, it can work! You should follow the "Download URL" visible at pypi project page (i.e. https://sourceforge.net/projects/pywin32/files/pywin32/ ) and install latest build. I just installed build 219 for Py3.4, as I myself also use this Python version. On the page installers are provided for several Python versions for 32bit and 64bit Windows.
Also, I've tweaked the code from above-linked SO answer to work in Python 3:
import win32console
_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
def input_def(prompt, default=''):
keys = []
for c in str(default):
evt = win32console.PyINPUT_RECORDType(win32console.KEY_EVENT)
evt.Char = c
evt.RepeatCount = 1
evt.KeyDown = True
keys.append(evt)
_stdin.WriteConsoleInput(keys)
return input(prompt)
if __name__ == '__main__':
name = input_def('Folder name: ', 'it works!!!')
print()
print(name)
This works on my Windows machine... If this does not work on yours, can you provide the error message?
I have written a line editor which hopefully does what you are looking for. But it is a quick-and-dirty hack. It is Windows only and written with CPython 3.6.5 on Windows 10, so its use might be limited. It has been tested on codepage 1252 (ANSI Latin 1; Western European (Windows)) and codepage 65001 (utf-8). It is very basic and a bit sluggish as it is not speed-optimized. (I should rewrite it in C but I do not have the time.) It is hardly tested and poorly documented.
import msvcrt
import os
import sys
if os.name != 'nt':
raise NotImplementedError('This module works only on MS Windows!')
CTRL_00 = 0
CTRL_E0 = 224
KEY_BACKSPACE = 8
KEY_DELETE = 83 # CTRL
KEY_END = 79 # CTRL
KEY_ESC = 27
KEY_HOME = 71 # CTRL
KEY_INSERT = 82 # CTRL
KEY_LEFT = 75 # CTRL
KEY_RETURN = 13
KEY_RIGHT = 77 # CTRL
flush = sys.stdout.flush
write = sys.stdout.write
mode = ('[OVR]> ', '[INS]> ') # overwrite, insert
prefix = len(mode[0])
def _update_line(insert, source, length, line, target):
"""Write a new line and position the cursor.
source: previous cursor position
length: old line length
line: edited line
target: next cursor position
"""
write('\b' * source) # set cursor to start of line
write(' ' * length) # erase old line
write('\b' * length) # again, set cursor to start of line
write(mode[insert] + line[prefix:]) # write updated line
write('\b' * (len(line) - target)) # set cursor to new position
flush() # write buffer to screen
def mswin_line_edit(default_string, insert=True):
"""Edit a MS Windows CLI line."""
insert = insert
line = mode[insert] + default_string
count = len(line)
before = line[:count]
after = line[count:]
print(line, end='', flush=True)
cursor = count
while True:
key = msvcrt.getwch()
num = ord(key)
if num == KEY_ESC: # abort edit
return default_string
if num == KEY_RETURN: # finish edit
return line
if num == KEY_BACKSPACE: # delete character before cursor
if cursor > prefix:
before = line[:cursor - 1]
after = line[cursor:]
line = before + after
_update_line(insert, cursor, count, line, cursor - 1)
cursor -= 1
count = len(line)
elif num == CTRL_E0 or num == CTRL_00: # CTRL
ctrl = ord(msvcrt.getwch())
if ctrl == KEY_END: # set cursor after last character
if cursor < count:
before = line
after = ''
_update_line(insert, cursor, count, line, count)
cursor = count
elif ctrl == KEY_HOME: # set cursor before first character
if cursor > prefix:
before = ''
after = line
_update_line(insert, cursor, count, line, prefix)
cursor = prefix
elif ctrl == KEY_LEFT: # move cursor 1 character to the left
if cursor > prefix:
before = line[:cursor]
after = line[cursor:]
_update_line(insert, cursor, count, line, cursor - 1)
cursor -= 1
elif ctrl == KEY_RIGHT: # move cursor 1 character to the right
if cursor < count:
before = line[:cursor]
after = line[cursor:]
_update_line(insert, cursor, count, line, cursor + 1)
cursor += 1
elif ctrl == KEY_DELETE: # delete character after cursor
if cursor < count:
before = line[:cursor]
after = line[cursor + 1:]
line = before + after
_update_line(insert, cursor, count, line, cursor)
count = len(line)
elif ctrl == KEY_INSERT: # switch insert/overwrite mode
insert ^= True
_update_line(insert, cursor, count, line, cursor)
else: # ordinary character
before = line[:cursor] + key
if insert:
after = line[cursor:]
else:
after = line[cursor + 1:]
line = before + after
_update_line(insert, cursor, count, line, cursor + 1)
cursor += 1
count = len(line)
if __name__ == '__main__':
test_string = input('test string: ')
result = mswin_line_edit(test_string)
print(f'\n{result}')
You could do it with tkinter:
from tkinter import *
def enter():
global commandEntry
command = commandEntry.get()
# Do stuff with command
commandEntry.delete(0, END)
def edit_line(line):
global commandEntry
commandEntry.insert(0, line)
root = Tk()
messageVar = StringVar()
messageVar.set("Enter a command:")
message = Label(root, textvariable=messageVar)
commandEntry = Entry(root)
enterButton = Button(root, text="Enter", command=enter)
root.mainloop()
You should just have 2 variables: one for standard string, one for string that will user change by itself.
Like:
str1 = 'String that is standard'
str2 = str1 #it usually will be standard string
usr = input('your text goes here')
if len(usr) != 0:
str2 = usr
#and here goes code for writing string into file

Categories

Resources