Getting my Python program to run Power Shell Script - python

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

Related

Getting skipped out of the loop without letting me type

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.

Remove prompt from console after user enters text with input() [duplicate]

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)

Variable prints in main method but when called in while loop it does not print. How can I resolve this issue?

So my script is working for pulling up the menu but when I pick and option it does not catch the variable outside the main method. I know I just may be doing something small wrong or not can anyone see what my issue is. Much appreciated in advance.
## 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
## Directory Enumerator
fileFolderLocationFilter = os.listdir('C:\\Users\\myFiles\\Documents\\_Scripts\\MyScripts\\')
selectedFile=""
## Menu defined setting veriables
def My_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 (47 * "_")
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
else:
selectedFiles = enumFiles[choice]
print(selectedFiles[1])
selectedFile = selectedFiles[1]
return choice
##initiating loop
loop = True
while loop:
choice = My_menu()
print (choice)
print ("---" +str(selectedFile))

2 programs playing against eachother

I'm currently writing 2 programs in python that must play a number game against each other. One program picks a number between 1 and 100. Then the other attempts to guess what that number is. Each time the guesser gives it's guess, the chooser then replies with 'too big', 'too small', or 'you got it'. According to what the reply is the guesser adjusts its next guess accordingly.
Here's my code for the program that chooses:
import random
from guesser import g
guessCount = 0
number = random.randint(1, 100)
print("I'm thinking of a number between 1 and 100.")
outfile = open ('response.txt', 'w')
guess = 50
print (guess)
if guess < number:
print('Your guess is too low.')
switch = '1'
outfile.write (switch + '\n')
elif guess > number:
print('Your guess is too high.')
switch = '2'
outfile.write (switch + '\n')
else:
print('Correct, You guessed the number in', guessCount, 'guesses.')
switch = '3'
outfile.write (switch + '\n')
while guessCount < 8:
guess = g
print (guess)
guessCount += 1
if guess < number:
print('Your guess is too low.')
switch = '1'
outfile.write (switch + '\n')
elif guess > number:
print('Your guess is too high.')
switch = '2'
outfile.write (switch + '\n')
else:
print('Correct, You guessed the number in', guessCount, 'guesses.')
switch = '3'
outfile.write (switch + '\n')
break
outfile.close()
print('The number was',number)
And here's the code for the program that gives the guesses:
low = 1
high = 100
guess = 0
guessCounter = 0
infile = open ('response.txt', 'r')
switch = int (infile.readline())
def g (switch):
while switch != 3 and guessCounter < 8:
guess = (low+high)//2
guessCounter += 1
if switch == 1:
high = guess
elif switch == 2:
low = guess + 1
return guess
My main question is how to get the 2 programs to interact with eachother. I'm currently trying to use a method of having them communicate through a text file called response, but surely there's an easier way?
The main problem I'm having it seems is that when chooser tries to get the variable g from guesser it can't because there's no response currently in response.txt meaning switch = int ('')
Traceback (most recent call last): File
"C:\Users\Jash\Downloads\guesser.py", line 8, in
switch = int (infile.readline()) ValueError: invalid literal for int() with base 10: ''
And yes, they must be 2 separate programs. And it must be done in python.
It would be a lot easier to put both players in the same program.
If you really want to use 2, though, you can run them like this on unix or linux:
echo "" > somefile
tail -f somefile | program1 | program2 >> somefile
This will effectively pipe each program's output into the other's input. Of course anything you want to see should be printed to standard error.
You can open the child scripts from your main script like this:
from subprocess import Popen, PIPE
prog = Popen("child.py", shell=True, stdin=PIPE, stdout=PIPE)
prog.stdin.write("Message to child.py maybe from another child?\n")
print prog.stdout.read() #Response from child
prog.wait() # Wait for script to finish run next script
as mentioned by Matt Timmermans:
if it is not absolutely neccessary, put the whole logic into one program:
import random
def createNum():
return random.randint(1,101)
lastGuess = 0
randMin, randMax = 1, 101
def guessNum(sigmoidAdjustmentInt):
# sigmoidAdjustmentInt represents a number which is negative, equal to zero or positiv; e.g. [-1 / 0 / +1]
# 0 == no information about to big or to small number
# -1 == number has to be smaller this time
# 1 == number has to be bigger this time
# guess somehow; e.g. with random again
if sigmoidAdjustmentInt < 0:
randMax = lastGuess-1
elif 0 < sigmoidAdjustmentInt:
randMin = lastGuess+1
return random.randint(randMin,randMax)
def main():
secretNumber = createNum()
guessedCorrectly = False
triesCounter = 0
sigmoidAdjustmentInt = 0 # set here for the first call
while not guessedCorrectly:
triesCounter = 0
if guessNum(sigmoidAdjustmentInt) == secretNumber:
guessedCorrectly = True
break
# print here if too high or low
print("needed guesses: "+ triesCounter)
# do something else
please note that the random.randint(...)-calls of createNum and guessNum are only placeholders for your preferred implementations of it.
see also: random.randint
as for your question how to execute multiple scripts.
say you have 3 files:
a.py
b.py
c.py
you start a.py, it does something, calls b.py and after that calls c.py with the result.
you can do it this way:
# in a.py
import subprocess
args = ( # rebuild the commandline call of the file here; the following stands for the comandline command: python b.py
"python", # every whitespace in the cmd-command is a comma in this args-tuple
"b.py"
)
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
resultsOfB, errorsOfB = popen.communicate()
del popen
args = ( # this represents: python c.py someStringValueContainedInResultFromB
"python",
"c.py",
resultOfB # lets just say this var contains a string => if not convert it to one
)
popen = subprocess.Popen(args, stdout=subprocess.PIPE)
popen.wait()
resultsOfC, errorsOfC = popen.communicate()
# do something with the results of c.py
again: if you write all three of the files, consider to put them together into one. this method is good if you have to call third party software or something like that (e.g.:)
Create a third, referee program. Take two arguments - the names of the picker and the guesser programs. Have the referee program open read/write pipes to the two programs, and using either the subprocess or the pexpect module.

Python Application does nothing

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.

Categories

Resources