Pythin: Kill a process while not accessing it - python

This has been a head twister, here is what I am trying to do
Function1: Calls an API for an integer
Function2: Based on the API result, it will play a ffmpeg radio station
This works on its own, the problem happens when the integers changes
This is how it should work
API = 1 -> Play Radio 1 -> API = 1 -> Continue Playing Radio 1 -> API = 2 -> Play Radio 2
My main:
def currentlyPlaying(num):
if num == 1:
musicPlay = subprocess.call(["ffplay", "-nodisp", "http://n0e.radiojar.com/8s5u5tpdtwzuv?rj-ttl=5&rj-tok=AAABf8pZIfoAj4LUj-sLh_n6Vw"])
if num == 2:
musicPlay =subprocess.call(["ffplay", "-nodisp", "http://livstream.xyz:8220/radio.mp3"])
if num == 3:
musicPlay =subprocess.call(["ffplay", "-nodisp", "http://livstream.xyz:8050/radio.mp3"])
if num == 4:
musicPlay =subprocess.call(["ffplay", "-nodisp", "http://stream.zeno.fm/wcue1s1g6ehvv"])
if num == 5:
musicPlay =subprocess.call(["ffplay", "-nodisp", "http://livstream.xyz:8030/radio.mp3"])
if num ==6:
musicPlay =subprocess.call(["ffplay", "-nodisp", "http://livstream.xyz:8190/radio.mp3"])
if num == 7:
musicPlay =subprocess.call(["ffplay", "-nodisp", "https://server03.quran.com.kw:7000/;*.mp3"])
else:
print("Invalid Choice")
def kill(self):
sys.exit()
def mainFunction():
tempTrack = 1
while True:
response = requests.get("http://127.0.0.1:8000/currentTrack")
currentTrack = int(response.text)
time.sleep(1)
if tempTrack != currentTrack:
print("CHANGED")
#os.kill(os.getppid(), signal.SIGTERM)
tempTrack = currentTrack
if currentTrack == 0:
print("Fucker")
elif currentTrack == 1:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(1)
elif currentTrack == 2:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(2)
elif currentTrack == 3:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(3)
elif currentTrack == 4:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(4)
elif currentTrack == 5:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(5)
elif currentTrack == 6:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(6)
elif currentTrack == 7:
print("\n Playing Track: ", currentTrack)
#currentlyPlaying(7)
elif currentTrack == 44:
kill()
else:
print("Invalid, try again")
Main is constantly checking API value, what I need it to do is continue checking API value, even after a radio is playing, and kill the radio and start a new one if a different API number is passed

Related

how to elimate the need for a large number of if elif else statements

My script uses a if elif else check to determine which array item to look at for crafting values. The issue is there are a total of 24 elif statements to allow for a total of 26 choices, (1 for the if, 1 for error catching). What I'm trying to figure out is how to reduce the number of elif statements so the code is better structured.
while choice == 0:
choice = input("Choose a block (Enter only the Number):")
if not choice.isalpha(): # Makes sure that the input is a number and not a string.
choice = int(choice)
else:
choice = 0
print("Thats not a number. Choose a number Numbnuts.")
if choice == 1:
print("\n",block[0])
elif choice == 2:
print("\n",block[1])
elif choice == 3:
print("\n",block[2])
elif choice == 4:
print("\n",block[6])
elif choice == 5:
print("\n",block[7])
elif choice == 6:
print("\n",block[8])
elif choice == 7:
print("\n",block[3])
elif choice == 8:
print("\n",block[4])
elif choice == 9:
print("\n",block[5])
elif choice == 10:
print("\n",block[9])
elif choice == 11:
print("\n", block[10])
elif choice == 12:
print("\n", block[11])
elif choice == 13:
print("\n",block[12])
elif choice == 14:
print("\n",block[13])
elif choice == 15:
print("\n",block[14])
elif choice == 16:
print("\n",block[15])
elif choice == 17:
print("\n",block[16])
elif choice == 18:
print("\n",block[17])
elif choice == 19:
print("\n",block[18])
elif choice == 20:
print("\n",block[19])
elif choice == 21:
print("\n",block[20])
elif choice == 22:
print("\n", block[21])
elif choice == 23:
print("\n", block[22])
elif choice == 24:
print("\n",block[23])
elif choice == 25:
print("\n",block[24])
elif choice == 26:
print("\n",block[25])
Look for structure:
elif choice == 12:
print("\n", block[11])
elif choice == 13:
print("\n",block[12])
elif choice == 14:
print("\n",block[13])
elif choice == 15:
print("\n",block[14])
elif choice == 16:
print("\n",block[15])
Clearly, this is the same as;
print("\n", block[choice - 1])
However, for choice in {4,5,6,7,8,9} the logic isn't that simple, so you could keep the ifs:
if choice == 4:
print("\n",block[6])
elif choice == 5:
print("\n",block[7])
elif choice == 6:
print("\n",block[8])
elif choice == 7:
print("\n",block[3])
elif choice == 8:
print("\n",block[4])
elif choice == 9:
print("\n",block[5])
else:
print("\n", block[choice - 1])
You could also go a step deeper: for choice in {4,5,6} the index is choice-2, and for choice in {7,8,9} the index is choice-4:
if choice in {4,5,6}:
idx = choice - 2
elif choice in {7,8,9}:
idx = choice - 4
else:
idx = choice - 1
print("\n", block[idx])
As another answer suggested, look for structure; you have different ranges of choices that correspond to different offsets in block, so you can iterate over those:
while True:
try:
choice = input("Choose a block (Enter only the Number):")
except ValueError:
print("Thats not a number. Choose a number Numbnuts.")
continue
if choice < 1 or choice > 26:
continue
print("\n")
for limit, offset in ((3, -1), (6, 2), (9, -4), (26, -1)):
if choice <= limit:
print(block[choice + offset])
break
break
Hence for 1 <= choice <= 3 you print block[choice-1], for 4 <= choice <= 6 you print block[choice+2], and so on.
my version:
block_2 = block[:3]+block[6:9]+block[3:6]+block[9:]
print("\n", block_2[choice - 1])

Can someone help me on what is wrong in my code. I'm trying to use getkey in python

I am trying to use getkey of python that I downloaded from github. But somehow my code is preventing me of achieving it. The keys.UP and keys.DOWN are not functioning, but when I tried to change the "and" in
if key == keys.DOWN and menu_selected + 1 != len(menu_option): to or then I manage the Down keys to work. But the problem is, it won't let me use the Up keys.
Below, are the part of the code I'm talking about. Thank you in advance guys!
from getkey import getkey, keys
import os
def first_choice():
os.system('cls')
print("\nFörsta valet")
input("Press Enter to continue....")
def second_choice():
os.system('cls')
print("\nAndra valet")
input("Press Enter to continue....")
def third_choice():
os.system('cls')
print("\nTredje valet")
input("Press Enter to continue....")
def end_program():
os.system('cls')
print("\nAvsluta programmet")
input("Press Enter to continue....")
menu_option = ["Förstaval\t\t", "Andraval\t\t", "Tredjeval\t\t", "Avsluta\t\t"]
menu_selected = 0
while True:
os.system('cls')
print("\x1b[?25l")
if menu_selected == 0:
print(menu_option[0] + "<--")
print(menu_option[1])
print(menu_option[2])
print(menu_option[3])
elif menu_selected == 1:
print(menu_option[0])
print(menu_option[1] + "<--")
print(menu_option[2])
print(menu_option[3])
elif menu_selected == 2:
print(menu_option[0])
print(menu_option[1])
print(menu_option[2] + "<--")
print(menu_option[3])
elif menu_selected == 3:
print(menu_option[0])
print(menu_option[1])
print(menu_option[2])
print(menu_option[3] + "<--")
key = getkey()
if key == keys.DOWN and menu_selected + 1 != len(menu_option):
menu_selected += 1
elif key == keys.UP and not (menu_selected == 0):
menu_selected -= 1
elif key == keys.ENTER:
if menu_selected == 0:
first_choice()
elif menu_selected == 1:
second_choice()
elif menu_selected == 2:
third_choice()
elif menu_selected == 3:
end_program()
break
Output:

Need help on why my black jack game Getting 'IndexError: pop from empty list' Error

I was trying to make a blackjack game and when I When I enter H or D for the choice input, the console doesn't allow any of my inputs apart from Ctrl+C for output1 and it produces an error shown in ouput2 when I enter S for the choice input
My code
from random import choice, shuffle
plain_cards = ['2','3','4','5','6','7','8','9','J', 'K', 'Q', 'A']
HEARTS = chr(9829)
DIAMONDS = chr(9830)
SPADES = chr(9824)
CLUBS = chr(9827)
suits = [HEARTS,DIAMONDS,SPADES,CLUBS]
def get_deck():
deck = [(suit, card) for suit in suits for card in plain_cards]
shuffle(deck)
return deck
def get_cards_value(cards):
total = 0
aces = []
for card in cards:
if card[1].isdigit():
total += int(card[1])
if card[1] == 'K' or card[1] == 'J' or card[1] == 'Q':
total += 10
if card[1] == 'A' :
total += 11
aces.append('A')
for i in aces:
if total > 21:
total -= 10
return total
def game():
print('Welcome to BLACK JACK')
money = 1000
playing = True
game_on = True
while playing:
if money <= 0:
playing = False
print('Thanks for playing but your money is done come back soon')
else:
bet = input('Stake: ')
if not bet.isdigit():
print('Invalid input')
continue
elif int(bet) > money:
print('You don\'t have enough money')
continue
else:
bet = int(bet)
deck = get_deck()
player_hand = [deck.pop(), deck.pop()]
dealer_hand = [deck.pop(), deck.pop()]
print('Player hand')
print(f'{player_hand} total:{get_cards_value(player_hand)}')
print('Dealer Hand')
print(f'[{dealer_hand[0]}, ###]')
player_total = get_cards_value(player_hand)
dealer_total = get_cards_value(dealer_hand)
while game_on:
if player_total > 21 or dealer_total > 21:
break
choice = input('(S)tand, (D)ouble, (H)it: ')
if choice == 'D':
bet *= 2
money += bet
if choice == 'D' or choice == 'H':
new_card = deck.pop()
player_hand.append(new_card)
break
if choice == 'S':
break
if player_total < 21:
while dealer_total < 17:
new_card = deck.pop()
dealer_hand.append(new_card)
if player_total == 21:
print('You won')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money += bet
elif dealer_total == 21:
print('You lost')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money -= bet
elif player_total > dealer_total:
print('You lost')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money -= bet
elif player_total < dealer_total:
print('You win')
print(f'Player>>{player_hand} total:{get_cards_value(player_hand)}')
print(f'Dealer>>{dealer_hand} total:{dealer_total}')
money += bet
game()
This the output when I enter S,H or D
Traceback (most recent call last):
File "C:/Users/Godfrey Baguma/AppData/Local/Programs/Python/Python39/ssdd.py", line 109, in <module>
game()
File "C:/Users/Godfrey Baguma/AppData/Local/Programs/Python/Python39/ssdd.py", line 82, in game
new_card = deck.pop()
IndexError: pop from empty list
The answer's in the error output there. Specifically, in this block:
if player_total < 21:
while dealer_total < 17:
new_card
dealer_hand.append(new_card)
You didn't set the value of new_card (did you mean to make it new_card = deck.pop()?), so the interpreter has no idea what to do with it and errors out.
The error says that you want to access a variable that is not yet known. There is a bug in your code (line 82 or 83). The program flow can take place in such a way that dealer_hand.append(new_card) is called but new_card is not yet known.
There is an infinite loop:
while dealer_total < 17:
new_card = deck.pop()
dealer_hand.append(new_card)
dealer_total is not updated, so the deck runs out of cards and throws the IndexError.

My main function is repeating in an infinite loop and I do not know why

I am running a program that plays rock, paper, scissors. I have executed the code multiple times and everytime I do, the input asking the user to pick 0,1,2 repeats more than one time. It is only supposed to be asked one time per game cycle. Can anyone help me figure out why this is happening, and how to fix it?
import random
# Function: Display Menu
# Input: none
# Output: none
# displays the game rules to the user
def displayMenu():
print("Welcome! Let's play rock, paper, scissors.")
print("The rules of the game are:")
print("\tRock smashes scissors")
print("\tScissors cut paper")
print("\tPaper covers rock")
print("\tIf both the choices are the same, it's a tie")
# Function: Get Computer Choice
# Input: none
# Output: integer that is randomly chosen, a number between 0 to 2
def getComputerChoice():
computerChoice = random.randrange(0,3)
return computerChoice
# Function: Get Player Choice
# Input: none
# Output: integer that represents the choice
# Asks the user for their choice: 0 for rock, 1 for paper, or 2 for scissors
def getPlayerChoice():
playerChoice = int(input("Please choose (0) for rock, (1) for paper or (2) for scissors"))
return playerChoice
# Function: Play Round
# Input: two integers--one representing the computer's choice and the other representing the player's choice
# Output: integer (-1 if computer wins, 1 if player wins, 0 if there is a tie)
# This method contains the game logic so it stimulates the game and determines a winner
def playRound(getcomputerChoice, getplayerChoice):
if getplayerChoice == 0 and getcomputerChoice == 2:
return 1
elif getcomputerChoice == 0 and getplayerChoice == 2:
return -1
elif getplayerChoice == 2 and getcomputerChoice == 1:
return 1
elif getcomputerChoice == 2 and getplayerChoice == 1:
return -1
elif getplayerChoice == 1 and getcomputerChoice == 0:
return 1
elif getcomputerChoice == 1 and getplayerChoice == 0:
return 1
else:
return 0
# Function: Continue Game
# Input: none
# Output: boolean
# Ask the user is they want to continue (Y/N), and then return True or False accordingly
def continueGame():
playAgain = input("Do you want to continue playing? Enter (y) for yes or (n) for no.")
if playAgain.lower() == "y":
return True
elif playAgain.lower() == "n":
return False
# Function: main
# Input: none
# Output: none
def main():
displayMenu()
getPlayerChoice()
if getPlayerChoice() == 0:
choicePlayer = "rock"
elif getPlayerChoice() == 1:
choicePlayer = "paper"
elif getPlayerChoice() == 2:
choicePlayer = "scissors"
getComputerChoice()
if getComputerChoice() == 0:
choiceComputer = "rock"
elif getComputerChoice() == 1:
choiceComputer = "paper"
elif getComputerChoice() == 2:
choiceComputer = "scissors"
print("You chose", choicePlayer + ".")
print("The computer chose", choiceComputer + ".")
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
while continueGame() == True:
displayMenu()
getPlayerChoice()
getComputerChoice()
playRound(getComputerChoice(), getPlayerChoice())
continueGame()
playerCounter = 0
computerCounter = 0
tieCounter = 0
while playRound(getPlayerChoice(), getPlayerChoice()) == -1:
computerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 1:
playerCounter += 1
while playRound(getPlayerChoice(), getPlayerChoice()) == 0:
tieCounter += 1
print()
print("You won", playerCounter, "game(s).")
print("The computer won", computerCounter, "game(s).")
print("You tied with the computer", tieCounter, "time(s).")
print()
print("Thanks for playing!")
# Call Main
main()
It's because when you do:
if getPlayerChoice() == 0:
choicePlayer = "rock"
You are actually calling the method again.
You should do:
p_choice = getPlayerChoice()
if p_choice == 0:
...

Python 3 IndentationError

In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
print("--------")
print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
print("--------")
print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])
def choose_player():
while True:
player = input("What do you want to be; X or O?")
if player == "X":
print("You chose X")
comp = "O"
break
elif player == "O":
print("You chose O")
comp = "X"
break
else:
print("Invalid Selection")
continue
return [player, comp]
def virtual_toss():
print("Tossing to see who goes first.....")
x = random.randint(0,1)
if x== 0:
print("AI goes first")
move = "comp"
if x == 1:
print("Human goes first")
move = "hum"
return move
def win(board,le):
if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
return True
else:
return False
def make_move(board,number,symbol):
board[number] = symbol
def board_full(board):
count = 0
for item in board:
if item in ["X","O"]:
count+= 1
if count ==9 :
return True
else:
return False
def valid_move(board,num):
if board[num] == " ":
return True
else:
return False
def player_move(board):
number = int(input("Enter the number"))
return number
def copy_board(board):
copied_board = copy.copy(board)
return copied_board
def check_corner(board):
if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
return True
else:
return False
def check_center(board):
if (board[5] == " "):
return True
else:
return False
while True:
count = 0
loop_break = 0
print("welcome to TIC TAC TOE")
pla,comp = choose_player()
turn = virtual_toss()
while True:
printboard(the_board)
if turn == "hum":
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break == 6:
continue
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
else:
if board_full() == True:
again = input ("Game is a tie. Want to try again? Y for yes and N for No")
if again == "Y":
loop_break = 6
break
else:
system.exit()
if loop_break = 6:
continue
copy_board(the_board)
for i in range(0,9):
make_move(copied_board,i,pla)
if(win(copied_board,pla) == True):
make_move(the_board,comp)
turn = "hum"
loop_break = 1
break
else:
continue
if loop_break = 1:
continue
if (check_corner(the_board) == True) or (check_center(the_board)==True):
for i in [7,9,1,3,5]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)==True):
make_move(the_board,i,comp)
print("The AI beat you")
loop_break = 2
count = 1
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 3
break
if loop_break == 2:
break
elif loop_break == 3:
continue
else:
for i in [8,4,6,2]:
if(valid_move(copied_board,i)==True):
make_move(copied_board,i,comp)
if(win(copied_board,comp)):
make_move(the_board,i,comp)
print("The AI beat you")
count = 1
loop_break = 4
break
else:
make_move(the_board,i,comp)
turn = "hum"
loop_break = 5
break
if loop_break == 4:
break
elif loop_break == 5:
continue
if count == 1:
again = input("Would you like to play again? y/n")
if again == "y":
continue
else:
system.exit()
I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
Traceback (most recent call last):
File "python", line 106
if (win(the_board,pla) == True):
^
IndentationError: unindent does not match any outer indentation level
More specifically, this part of the code:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
Any help? I cannot get the code to work by any means!!
Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
You need to indent the block under while (True): consistently. E.g.:
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break
else:
turn = "comp"
printboard(the_board)
continue
The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
number = player_move(the_board)
if (valid_move(the_board,number) == True) and not(board_full == False):
make_move(the_board,number,pla)
break
else:
print("Invalid Move, try again!")
continue
if (win(the_board,pla) == True):
print ("Yay, you won!!!")
printboard(the_board)
count = 1
break

Categories

Resources