buscar valor en lista Objeto python

A ver si me podéis echar un cable. Estoy intentando comprobar si existe un valor en una lista. No controlo de Python y no consigo sacarlo. Esto es lo que tengo,

[{‘nodo1’: {‘openfiles’: [], ‘resume’: None, ‘total’: 0}},
{‘nodo2’: {‘openfiles’: [{‘file’: ‘file1’,
‘id’: 25159713,
‘locks’: 0,
‘permissions’: [‘read’],
‘user’: ‘user-1’}],
‘resume’: None,
‘total’: 1}},
{‘nodo3’: {‘openfiles’: [{‘file’: ‘file1’,
‘id’: 42608352,
‘locks’: 0,
‘permissions’: [],
‘user’: ‘user-2’},
{‘file’: ‘file2’,
‘id’: 42608377,
‘locks’: 0,
‘permissions’: [],
‘user’: ‘user-3’}],
‘resume’: None,
‘total’: 6}}]

Necesito comprobar si existe el valor file y en caso de que así sea me devuelva los valores de ese objeto.

si hago esto llego a comprobar el valor “nodo” pero no consigo llega a file.

if nodo in result[0]:

En resumen, ¿como llegaria a comprobar el valor de file y recuperar ese objeto?

Os agradezco la ayuda :]

python: subprocess opening filles – Code Review Stack Exchange

I am using 2 functions written in python to convert DLG file to PDB energies

import glob
import os
import subprocess
import numpy as np
from vmd import vmdnumpy as vnp
from vmd import Molecule
from vmd import atomsel

def dlg_to_multiframepdb(fname):
        inputstrings = subprocess.check_output("grep "DOCKED:" %s" % fname, shell=True).decode().split("n")
        output = ""
        for s in inputstrings:
                if s(8:12) == "ATOM" or s(8:12) == "HETA":
                        output += s(8:) + "n"
                elif s(8:14) == "ENDMDL":
                        output += "ENDMDLn"
        return output
        
def dlg_to_energy(fname):
        inputstrings = subprocess.check_output("grep "Estimated" %s | sed 's/=//g' | awk '{print $8}'" % fname, shell=True).decode().split("n")(:-1)
        energies = np.array(inputstrings).astype(np.float)
        return energies

# simple code: loop over the directory of DLG filles and convert each file to PDB
pwd = os.getcwd()
dlg= 'dlg'
#set directory to analyse
data = os.path.join(pwd,dlg) 

dirlist = (os.path.basename(p) for p in glob.glob(data + '/*.dlg'))
os.chdir(data)
for dlg_file in dirlist: 
      energies = dlg_to_energy(dlg_file)
      pdb = dlg_to_multiframepdb(dlg_file)

Briefly, the first function take some part from the initial file using shell utility GREP, skipping some unused strings; and the second function – use GREP + SED to take specific strings from the same file and store it as numpy array. How the code could be further improved?

Dealing cards for a game – my first Python project

I am new to Python but I aspire to become a ‘proper’ Python coder, (maybe even one day help the noobs on CodeReview 🙂

Therefore I want to get into good habits early, and would really appreciate some feedback on my first mini-project.

Notes

  1. The code deals cards for a simple board game. If you are interested, this is explained in more detail below under ‘Rules’. Full game rules here.
  2. There are no bugs or problems I can detect.
  3. I have made extensive use of tkinter as a means-to-an-end, however I am less interested in tkinter-specific feedback, but rather the fundamentals of Python itself: classes/objects, decorators, scope, code design/efficiency/elegance. Please point out any barn-door design mistakes, stylistic shortfalls, areas for improvement.
  4. I know i need to change some function names in line with PEP.

Rules (What the Code Does)

  • The user selects their team type and team colour from ‘launch window’.
  • A ‘game window’ then appears, showing two decks of shuffled cards, ‘R’ and ‘S’, 15 per deck.
  • User can click either deck to draw a hand of 4 cards.
  • User can click on any of the 4 cards to ‘play’ the card, whereafter the card is discarded from the game, and the 3 remaining cards are set aside in a hidden ‘recycle’ deck (one for R, one for S).
  • When fewer than 4 cards remain in either of the main ‘R’ or ‘S’ decks, the R or S hidden recycled deck is shuffled and its cards are re-added to the bottom of the respective ‘R’ or ‘S’ main deck, and can be drawn on demand, as before.
  • Sometimes, a user is compelled to collect an ‘exhaustion’ card for R or for S, which is placed directly into the respective hidden recycle deck.
  • If the user can not draw 4 cards even after replenishing the R or S deck with its respective hidden recycle deck, the shortfall is made up by taking further ‘exhaustion’ cards as required.
  • There is no mixing between R and S decks.
  • Local image files of the cards are used as the ‘buttons’, so they can click on the card they want to choose it.

That’s it! Simple stuff. The game itself is not coded here. The reason for the lengthy code is mainly due to the graphical elements.


The Code

Am I using @property appropriately/excessively/unneccessarily below?

################
# GameLogic.py #
################
import random

# Global constants
# (The lists represent the decks, the elements are the numbers shown on each card.
ROULEUR = (3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 7, 7, 7)
SPRINTER =(2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 9, 9, 9)


class Deck:
    def __init__(self, team: str, rider: str, teamtype: str):
        self._team = team
        self._rider = rider
        self._cards = ()
        self._teamtype = teamtype

    @property
    def show(self):
        i = 0
        total = self.count_cards
        for crd in self.cards:
            i += 1
            print(f'Value of card {i} of {total} in {self.team} {self.rider} deck is {crd.value}')
            if not isinstance(self,MainDeck):
                print('This is not the main deck')
    # Getters
    @property
    def team(self):
        return self._team

    @property
    def rider(self):
        return self._rider

    @property
    def cards(self):
        return self._cards  # Returns list of Card objects

    @property
    def teamtype(self):
        return self._teamtype

    # Functions
    def get_card(self, index: int):
        return self.cards(index)

    @property
    def count_cards(self):
        return len(self.cards)

    def pick_cards(self, num: int):
        return self.cards(0:num)

    @property
    def shuffle(self):
        for i in range(self.count_cards -1, -1, -1):
            rnd = random.randint(0, i)
            self.cards(i), self.cards(rnd) = self.cards(rnd), self.cards(i)

    def add(self, newCard: object):
        self.cards.append(newCard)

    def remove_card(self, index: int):
        return self.cards.pop(index)

    @property
    def countExhaustion(self) -> int:
        cnt = 0
        for crd in self.cards:
            if isinstance(crd, ExhaustCard):
                cnt += 1
        return cnt

    def getFilePaths(self) -> str:
        filepaths = ()
        for card in self.cards:
            if isinstance(card,ExhaustCard):
                filepaths.append(f'Images/exhaust_{self.rider(0:1).upper()}_{str(card.value)}.jpg')
            else:
                filepaths.append(f'Images/{self.team.lower()}_{self.rider(0:1).upper()}_{str(card.value)}.jpg')
        return filepaths

    # For a given card(index = i), return a tuple with all the remaining original indices of the other cards in that deck. Used for recycling hands of variable size. Reverse order for ease of processing later.
    def getRemainders(self, i: int) -> int:
        indices = list(range(self.count_cards))
        del indices(i)
        return indices(::-1)

class MainDeck(Deck):
    def __init__(self, team: str, rider: str, teamtype: str):
        self._team = team
        self._rider = rider
        self._cards = ()
        self._teamtype = teamtype
        self._recycleDeck = Deck(team,rider,teamtype)

        if self.teamtype.lower() == 'player':
            if rider(0:1).upper() == 'R':
                for i in range(len(ROULEUR)):
                    self._cards.append(Card(ROULEUR(i)))
            elif rider(0:1).upper() == 'S':
                for i in range(len(SPRINTER)):
                    self._cards.append(Card(SPRINTER(i)))

    @property
    def recycleDeck(self):
        return self._recycleDeck

    def recycle(self, index: int):
        self.recycleDeck.cards.append(self.remove_card(index))

    def refresh_deck(self):
        self.recycleDeck.shuffle  # Shuffle the recycled cards (not those remaining in main deck)
        for i in range(self.recycleDeck.count_cards -1, -1,-1): # Add the shuffled recycled cards back in to the back of the main deck
            self.cards.append(self.recycleDeck.remove_card(i))


class Card():
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

class ExhaustCard(Card):
    def __init__(self):
        self._value = 2


# TO DO:
# - error handling on init verificaction

By contrast the file below feels bloated and messy. There must be a cleaner way to perform the interactive image initialisation instead of laboriously coding each item individually?

############
# GUI Module
############
import tkinter as tk
from PIL import Image, ImageTk
import GameLogic as GL
from tkinter import messagebox


# Constants
CARD_W = 180
CARD_H = 300
W_MULT = 1.2
TEAMS = ('Blue', 'Red', 'Green', 'Black', 'White', 'Pink')
RIDERS = ('Rouleur', 'Sprinter')
PLAYER = ('Player', 'Bot: Muscle Team', 'Bot: Peloton Team')
HANDSIZE = 4
DECK_PATHS = ('deck_main_R', 'deck_exhaust_R', 'FR_logo', 'deck_main_S', 'deck_exhaust_S')


##################
# LaunchWindow Class
##################
class LaunchWindow:

    def __init__(self, master):
        self.master = master

        # Make the frames
        self.frm_header = tk.Frame(self.master)
        self.frm_options = tk.Frame(self.master)
        self.frm_colour = tk.Frame(master=self.frm_options)
        self.frm_player = tk.Frame(master=self.frm_options)
        self.frm_footer = tk.Frame(master=self.master)

        # (1) Header widgets
        tk.Label(master=self.frm_header, text='Flamme Rouge', anchor=tk.NW, font=('Verdana', 50), fg='red').pack(side=tk.TOP, pady=10, padx=10)
        tk.Label(master=self.frm_header, text='Select team type options', anchor=tk.NW, font=('Verdana', 25)).pack(side=tk.TOP,pady=5)

        # (2) Team Choice Widgets
        #   (A) Team Colour Choice Input
        colour_choice = tk.StringVar()
        tk.Label(master= self.frm_colour, text='Team colour:').pack(side=tk.TOP, pady = 3)
        for team in TEAMS:
            textcolour = 'White'
            if team == 'White' or team == 'Pink':
                textcolour = 'Black'
            rb_teams = tk.Radiobutton(master= self.frm_colour, text=team, value=team, variable=colour_choice,  bg=team, fg=textcolour)
            rb_teams.pack(anchor=tk.N)

        #   (B) Player (Human or Bot) Choice Input
        player_choice = tk.StringVar()
        tk.Label(master=self.frm_player, text='Team Type:').pack(side=tk.TOP, pady=3)
        for p in PLAYER:
            rb_teams = tk.Radiobutton(master=self.frm_player, text=p, value=p, variable=player_choice, indicatoron=0)
            rb_teams.pack(anchor=tk.N)

        # (3)  Footer Widgets
        self.btn_start = tk.Button(master=self.frm_footer, text='Start Game', anchor=tk.S,
                                   relief=tk.RAISED, font=('Verdana', 35),
                                   command=lambda: self.start_game(colour_choice.get(), player_choice.get()),
                                   padx=20, pady=10).pack(side=tk.LEFT)
        self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S,  padx=20, pady=10,
                                   relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close).pack(side=tk.LEFT)

        #Pack the frames
        self.frm_header.pack(side=tk.TOP)
        self.frm_colour.pack(side=tk.LEFT)
        self.frm_player.pack(side=tk.LEFT)
        self.frm_options.pack(side=tk.TOP)
        self.frm_footer.pack(side=tk.BOTTOM, pady = 10)

    # Handle events, clicks etc
    def handle_close(self):
        self.master.destroy()

    def start_game(self, colour: str, team_type: str):
        self.master.destroy()
        game_window = tk.Tk()
        game = GameWindow(game_window, colour, team_type)



##################
# GameWindow Class
##################
class GameWindow:
    def __init__(self, master, colour, teamtype): # Create labels, entries,buttons
        self.master = master

        # Make the frames
        self.frm_header = tk.Frame(self.master)
        self.frm_decks = tk.Frame(self.master)
        self.frm_cards = tk.Frame(self.master)
        self.frm_footer = tk.Frame(self.master)

        # Initialise the Card decks according to user input on launch window
        self._deck_R = GL.MainDeck(colour, 'Rouleur', teamtype)
        self._deck_S = GL.MainDeck(colour, 'Sprinter', teamtype)
        self.deck_R.shuffle
        self.deck_S.shuffle

        # (1) Header Widgets
        tk.Label(master=self.frm_header, text=colour+' Team', fg=colour, bg='grey', anchor=tk.NW, font=('Verdana', 35, 'bold')).pack(side=tk.TOP, pady=10)

        # (2) Deck Widgets
        deck_images = ()
        deck_btns = ()
            # (a) Rouleur deck
        deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS(0)}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))
        deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images(0),
                                    command=lambda:self.show_hand(self.deck_R)))
        deck_btns(0).image = deck_images(0)
        deck_btns(0).grid(row=2, column=1, padx=20, pady=20)

            # (b) Rouleur Exhaustion
        deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS(1)}.jpg').resize((int(CARD_W*W_MULT), CARD_H))))
        deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W*W_MULT), height=CARD_H, image=deck_images(1),
                                    command=lambda:self.pickup_exhaust(self.deck_R.recycleDeck)))
        deck_btns(1).image = deck_images(1)
        deck_btns(1).grid(row=2, column=2, padx=20, pady=20)

            # (c) FR Logo
        deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS(2)}.jpg').resize((int(CARD_W*2), CARD_H))))
        deck_btns.append(tk.Label(master=self.frm_decks, width=int(CARD_W*2.2), height=CARD_H, image=deck_images(2)))
        deck_btns(2).image = deck_images(2)
        deck_btns(2).grid(row=2, column=3, padx=20, pady=20)

            # (d) Sprinter Deck
        deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS(3)}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))
        deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images(3),
                                   command=lambda: self.show_hand(self.deck_S)))
        deck_btns(3).image = deck_images(3)
        deck_btns(3).grid(row=2, column=4, padx=20, pady=20)

            # (e) Sprinter Exhaustion
        deck_images.append(ImageTk.PhotoImage(Image.open(f'Images/{DECK_PATHS(4)}.jpg').resize((int(CARD_W * W_MULT), CARD_H))))
        deck_btns.append(tk.Button(master=self.frm_decks, width=int(CARD_W * W_MULT), height=CARD_H, image=deck_images(4),
                                   command=lambda: self.pickup_exhaust(self.deck_S.recycleDeck)))
        deck_btns(4).image = deck_images(4)
        deck_btns(4).grid(row=2, column=5, padx=20, pady=20)

        # (f) Rouleur: deck label & card count
        tk.Label(master=self.frm_decks, text='Rouleur Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1,column=1)
        self.vR = tk.StringVar()
        tk.Label(master=self.frm_decks, textvariable=self.vR, font=('Verdana', 12), anchor=tk.N).grid(row=3,column=1)
        self.vRrec = tk.StringVar()
        tk.Label(master=self.frm_decks, textvariable=self.vRrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=1)

        # (g) Sprinter: deck label &  card count
        tk.Label(master=self.frm_decks, text='Sprinter Deck', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=4)
        self.vS = tk.StringVar()
        tk.Label(master=self.frm_decks, textvariable=self.vS, font=('Verdana', 12), anchor=tk.N).grid(row=3, column=4)
        self.vSrec = tk.StringVar()
        tk.Label(master=self.frm_decks, textvariable=self.vSrec, font=('Verdana', 12), anchor=tk.N).grid(row=4, column=4)

        # (h) Exhaustion labels
        tk.Label(master=self.frm_decks, text='Rouleur Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=2)
        tk.Label(master=self.frm_decks, text='Sprinter Exhaustion Cards', font=('Verdana', 20), anchor=tk.S).grid(row=1, column=5)

        # (4) Footer Widgets
        self.btn_close = tk.Button(master=self.frm_footer, text='Close', anchor=tk.S,
                                   relief=tk.RAISED, font=('Verdana', 25), command=self.handle_close,
                                   padx=10, pady=10).pack(side=tk.BOTTOM)

        # Pack the frames
        self.frm_header.pack(side=tk.TOP)
        self.frm_decks.pack(side=tk.TOP)
        self.frm_cards.pack(side=tk.TOP)
        self.frm_footer.pack(side=tk.BOTTOM)
        self.update_counts()

    ### END INIT

    #Properties, getters
    @property
    def deck_R(self):
        return self._deck_R

    @property
    def deck_S(self):
        return self._deck_S


    # Handle events, clicks etc
    def handle_close(self):
        self.master.destroy()

    def show_hand(self, deck: GL.MainDeck, num=HANDSIZE):
        # Check we have enough cards, if not, shuffle and reintroduce cards in the recycle deck
        if deck.count_cards < num:
            messagebox.askokcancel('information', f'You have used all your {deck.rider} cards!  Shuffling and reintroducing recycled cards...',)
            deck.refresh_deck()
            self.update_counts()

        hand = GL.Deck(deck.team, deck.rider, deck.teamtype)
        self.frm_cards.pack()

        for i in range(0,num):
            crd = deck.get_card(i)
            hand.add(crd)

        # Hand widgets
        imgs = hand.getFilePaths()
        hand_photos = ()
        for im in imgs:
            hand_photos.append(ImageTk.PhotoImage(Image.open(im).resize((CARD_W, CARD_H))))

        hand_btns = ()
        for i in range(len(imgs)):
            hand_btns.append(tk.Button(master=self.frm_cards, width=CARD_W, height=CARD_H,
                                       image=hand_photos(i),
                                       command=lambda i=i: self.playthecard(hand, i)))
            hand_btns(i).image = hand_photos(i)
            hand_btns(i).grid(row=1, column=i, padx=20, pady=20)

    # Pick up an exhaustion card and add to the recycle deck for that rider
    def pickup_exhaust(self, deck: GL.Deck, num=1):
        for i in range(0,num):
            answer = messagebox.askokcancel("Question", f'Collect an exhaustion card for your {deck.rider.upper()}?')
            if answer:
                ex_crd = GL.ExhaustCard()
                deck.add(ex_crd)
        self.update_counts()

    # Given a subdeck (e.g. a hand), returns the relevant main deck of cards, i.e. either the player's Rouleur deck or Sprinter Deck
    def getTargetDeck(self, D: GL.Deck) -> GL.MainDeck:
        if D.rider(0:1).upper() == 'R':
            return self.deck_R
        elif D.rider(0:1).upper() == 'S':
            return self.deck_S

    # Play the selected card; i.e. burn it, eliminate from the deck without recycling. Recycle the rest of the hand.
    def playthecard(self, hand: GL.Deck, i: int):
        answer = messagebox.askokcancel('information', f'Play the {hand.rider} {hand.get_card(i).value} card and recycle the other cards?', )
        if answer:
            currentDeck = self.getTargetDeck(hand)
            ToRecycle = hand.getRemainders(i)
            for index in ToRecycle:
                currentDeck.recycle(index) #Recycle the unused cards into recycle deck
            currentDeck.remove_card(0)  # Index 0 not index i. After remainder cards have been recycled (above), the first card in the Maindeck list will be that selected by the player.
            self.frm_cards.pack_forget()  # Clear the hand widgets from view (does not destroy!)
            self.update_counts()

    # Update the main deck card counts on the GUI
    def update_counts(self):
        self.vR.set(f'{self.deck_R.count_cards} cards in Rouleur deck')
        self.vS.set(f'{self.deck_S.count_cards} cards in Sprinter deck')
        self.vRrec.set(f'and {self.deck_R.recycleDeck.count_cards} recycled cards')
        self.vSrec.set(f'and {self.deck_S.recycleDeck.count_cards} recycled cards')

# Run it
def main():
    window = tk.Tk()
    app = GameWindow(window, 'Pink', 'Player')
    window.mainloop()

if __name__ == '__main__':
    print('GUI Main called')
    main()

And finally… this probably didn’t need a file of it’s own did it lololol..

import GUI
import tkinter as tk

# Launch the game window
window = tk.Tk()
app = GUI.LaunchWindow(window)
window.mainloop()

Thank you very much in advance!

beginner – Execute bunch of Http Api call using Python

I am working on a project where I need to work with http apis and call them using Python language. Below is what I need to do:

  • Take few input parameters like – environmentName, instanceName, configName.
  • Call get api on a service. Get the json data and compare the configName it already has vs what you want to update from the command line.
  • If config is same then don’t do anything and return back with a message.
  • But if config is different then post new json data with new configName passed from command line in it to the service using http api. In this there are two things:
    • We will make new json with new configName in it along with one more key which is action and value of that will be download. After successfully posting this new json then we will call another api (verifyApi) to verify whether all machines have downloaded successfully that config or not. If they downloaded successfully then we will move to the next step otherwise we will fail and return.
    • If all machines downloaded successfully, then we will change action key to verify in the same json and then we will post it again. After successfully posting this new json, we will call same verifyApi to make sure all machines have verified successfully.

Once everything is successful return otherwise fail it. Below is my code which does the job:

import requests
import json
import sys
import base64

# define all constants
actions=('download', 'verify')
endpoint="http://consul.{}.demo.com/"
config_path="v1/kv/app-name/{}/config"
status_path="v1/kv/app-name/{}/status/{}"
catalog_path="v1/catalog/service/app-name?ns=default&tag={}"
raw="?raw"

def update( url, json ):
    """
    This will make a PUT api call to update with new json config.
    """
    try:
        r = requests.put(url, data=json, headers={'Content-type': 'application/json'})
        r.raise_for_status()
        return True
    except requests.exceptions.HTTPError as errh:
        print ("Http Error:",errh)
    except requests.exceptions.ConnectionError as errc:
        print ("Error Connecting:",errc)
    except requests.exceptions.Timeout as errt:
        print ("Timeout Error:",errt)
    except requests.exceptions.RequestException as err:
        print ("OOps: Something Else",err)

    return False

def verify( environment, instance, config, action ):
    """
    This will get list of all ipAddresses for that instance in that environment.
    And then check whether each machine from that list have downloaded and verified successfully.
    Basically for each 'action' type I need to verify things.
    If successful at the end then print out the message.
    """
    flag = True
    catalog_url = endpoint.format(environment) + catalog_path.format(instance)
    response = requests.get(catalog_url)
    url = endpoint.format(environment) + status_path.format(instance) + raw
    json_array = response.json()
    count = 0
    for x in json_array:
        ip = x('Address')
        count++
        r = requests.get(url.format(ip))
        data = r.json()
        if action == 'download' and "isDownloaded" in data and data('isDownloaded') and "currentCfg" in data and data('currentCfg') == config:
            continue
        elif action == 'verify' and  "activeCfg" in data and data('activeCfg') == config:
            continue
        else:
            flag = False #set to False if above two if statements fail
            print("failed to " +action+ " on " +ip)

    if flag and action='download':
        print("downloaded successfully on all "+count+" machines")
    elif flag and action='verify':
        print("verified successfully on all "+count+" machines")

    return flag

def main():
    # capture inputs from command line
    environment = sys.argv(1)
    instance = sys.argv(2)
    new_config = sys.argv(3)

    # make url for get api to verify whether configs are same or not
    # as mentioned in point 1.
    url=endpoint.format(environment) + config_path.format(instance)
    response = requests.get(url + raw)
    data = json.loads(response.content)
    remote_config = data('remoteConfig')
    # compare remote_config in the json with config passed from command prompt
    if remote_config == new_config:
        print("cannot push same config")
        return

    # config is different
    data('remoteConfig') = new_config
    # now for each action, update json and then verify whether that action completed successfully.
    for action in actions:
        data('action') = action
        if update(url, json.dumps(data)):
            if verify(environment, instance, new_config, action):
                continue
            else:
                print(action+ " action failed")
                return
        else:
            print("failed to update")
            return


if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print("nCaught ctrl+c, exiting")

Problem Statement

I have my above code which works fine so opting for code review to see if there is any better way to do above things efficiently. I am also sure we can rewrite above things in much cleaner way compared to the way I have since I am relatively new to Python so I may have made lot of mistakes in designing it. Given this code will be run in production wanted to see what can be done to improve this.

Idea is something like this when I run it from command line.

If everything is successful then it should look like this:

python test.py dev master-instace test-config-123.tgz
downloaded successfully on all 10 machines
verified successfully on all 10 machines
config pushed successfully!!

In case of download failure:

python test.py dev master-instace test-config-123.tgz
failed to download on 1.2.3.4
failed to download on 4.2.3.4
download action failed

In case of verify failure:

python test.py dev master-instace test-config-123.tgz
failed to verify on 1.2.3.4
failed to verify on 4.2.3.4
verify action failed

python – ¿Por qué mi sentencia return True no funciona?

Este es un código el cual determina si un número es primo por medio de recursión, pero al ingresar un número primo no retorna True. Sin embargo, al ingresar un número compuesto sí retorna False.
¿Cómo puedo hacer que retorne True?

print("Veamos si el número que ingrese es primo.")
n = int(input("introduzca un número: "))
def funcion(n,b=2):
  b=b
  if type(n) != type(1):
    print("Por favor, ingrese un número entero")
  if n<2:
    return ("el número ha de ser mayor que dos")
  if b == n :
     return True
  else:
    if n % b == 0:
       return False
    else:
      funcion(n , b+1)
funcion(n)

python – Não existe nenhum erro na execução do código, porém o retorno que estou tendo na tabela do excel é que é o problema

Estou com um problema no retorno do meu código. Não me é retornado nenhum erro na execução, porém o problema disso é o retorno na tabela do Excel. Estou fazendo um estudo de caso da minha faculdade e o sistema se trata sobre o cadastro de clientes e encomenda. O código da classe e do objeto logo abaixo:

Classe


class Cliente:
    def __init__(self, nome, s_nome, tel, email, social_n, endereco, data_cad):
        self.set_nome(nome)
        self.set_s_nome(s_nome)
        self.set_tel(tel)
        self.set_email(email)
        self.set_social_n(social_n)
        self.set_endereco(endereco)
        self.set_data_cad(data_cad)

    # SETs dos dados do cliente

    def set_nome(self, nome):
        self.nome = nome

    def set_s_nome(self, s_nome):
        self.s_nome = s_nome

    def set_tel(self, tel):
        self.tel = tel

    def set_email(self, email):
        self.email = email

    def set_social_n(self, social_n):
        self.social_n = social_n
    
    def set_endereco(self, endereco):
        self.endereco = endereco

    def set_data_cad(self, data_cad):
        self.data_cad = data_cad

    # GET para retornar o "database"

    def get_database(self,rows):
        one_cliente = ()
        for n in range(rows):
            one_cliente.append({
                'id': n + 1,
                'nome':self.nome,
                'sobrenome':self.s_nome,
                'telefone':self.tel,
                'email':self.email,
                'rede_social':self.social_n,
                'endereco':self.endereco,
                'data_de_cadastro':self.data_cad
            })
        return one_cliente 

outro codigo


import os
import xlwt
import xlrd
from datetime import date
from class_cliente import Cliente

def main():
    cont = 1

    print('''
        O que deseja fazer?
        (1) Tabela de Clientes
        (2) Tabela de Encomendas
        (3) Excluir Cadastro
        (4) Relatório Excel
        (5) Sair
        ''')

    opcGeral = int(input('Digite Aqui: '))
    while True:
        if opcGeral == 1:

            nome = input('Nome do cliente: ')
            s_nome = input('Sobrenome do cliente: ')
            tel = input('Telefone pra conta: ')
            email = input('email: ')
            social_n = input('Rede: ')
            endereco = input('Endereço: ')                
            data_cad = date.today()

            workbook = xlwt.Workbook()
            worksheet = workbook.add_sheet("cliente")

            dado_cliente = Cliente(nome, s_nome, tel, email, social_n, endereco, data_cad)
            cont_cadas = dado_cliente.get_database(cont) 
            cont += 1

        elif opcGeral == 2:
            pass

        elif opcGeral == 4:
            worksheet.write(0,0,u'ID')
            worksheet.write(0,1,u'NOME')
            worksheet.write(0,2,u'SOBRENOME')
            worksheet.write(0,3,u'TELEFONE')
            worksheet.write(0,4,u'EMAIL')
            worksheet.write(0,5,u'REDE SOCIAL')
            worksheet.write(0,6,u'ENDEREÇO')
            worksheet.write(0,7,u'DATA DO CADASTRO')

            for i, cliente_one in enumerate(cont_cadas):
                worksheet.write(i + 1, 0, label = cliente_one('id'))
                worksheet.write(i + 1, 1, label = cliente_one('nome'))
                worksheet.write(i + 1, 2, label = cliente_one('sobrenome'))
                worksheet.write(i + 1, 3, label = cliente_one('telefone'))
                worksheet.write(i + 1, 4, label = cliente_one('email'))
                worksheet.write(i + 1, 5, label = cliente_one('rede_social'))
                worksheet.write(i + 1, 6, label = cliente_one('endereco'))
                worksheet.write(i + 1, 7, label = cliente_one('data_de_cadastro'),style=xlwt.easyxf(num_format_str='dd/mm/yyyy'))

            workbook.save('cliente.xls')


        opcGeral = input('Cadastrar mais clientes: (S/N)')
        if opcGeral.lower() == 's' :
            print('''
        O que deseja fazer?
        (1) Tabela de Clientes
        (2) Tabela de Encomendas
        (3) Excluir Cadastro
        (4) Relatório Excel
        (5) Sair
        ''')

            opcGeral = int(input('Digite Aqui: '))

        else:
            break

    
if __name__ == "__main__":
    main()

OBS: O segundo código ainda não esta terminado

Eu estou usando a lib xlwt para escrever no Excel só que quando vou executar o código quando começo a cadastrar os clientes fica normal e insere os dados normalmente, porém quando eu realizo dois cadastros ao invés de escrever no Excel as duas pessoas cadastradas ela acaba escrevendo duas vezes a ultima pessoa cadastrada… gostaria de saber o que estou fazendo de errado.

python – I am trying to get pandas to populate a cell using data from another cell in the same row and a for loop

import pandas as pd
import csv
from datetime import datetime
import random

pf = pd.read_csv(path, delimiter=',')  # for tests with original file
df = pd.read_csv('new_log.csv', delimiter=',')

for index, row in df.iterrows(): # iterate through rows in dataframe
    i = random.randint(0, 9) # select a random number for each row( This doesn't seem to do what I thought it would)
    if i > 6:  #  if the random number is high enough perform the operation
        row("IMC") = row("Block") * random.triangular(0, 1, 0)  # I want a column that already exists "IMC" to be populated by the value in the column "Block" multiplied by a random number
    else:   # if the random number is less than specified
        row("IMC") = 0
print(df)

df(“IMC”) = row(“Block”) * random.triangular(0, 1, 0) gives me almost what I want except it always provides a value greater than 0. I could round, but a bool would get me closer to what I want, which is why I am trying the for loop.

Result

IMC

NaN

NaN

NaN

My first problem is that the random number seems to only be chosen once instead of being chosen for each row, and I don’t really understand why.

My second problem is IMC has the value NaN. I tried writing it as df(row(IMC)) which gives me a separate NaN column with values in it.

I really want to know why the >i< is only being chosen once, instead of for each row. I would also like to know why I am not able to write any values into the dataframe as I have written it above.

I don’t know enough terminology to efficiently use the manual without ending up down a lot of irrelevant rabbit holes, so sorry for the basic level of the question.

Using postgres SQL in Python

I have been trying to improve python combined with Postgres.

At this moment im only sending two values to database which are etc:

link = "https://www.mathem.se/varor/vegetarisk-fars/vegofars-fairtrade-1000g-anamma"
store = "mathem" 

and I do have few options that I want to be able to do with Postgres and that is to fetch all, commit and count.

And here I do have few options such as to check if the link exists already, if its has been deactivated from before, delete the link, get the ID from the product etc etc:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
from datetime import datetime

import psycopg2

DATABASE_CONNECTION = {
    "host": "testing.com",
    "database": "test",
    "user": "test",
    "password": "test"
}


def execute_fetch_all(query):
    """
    Fetch all queries
    :param query:
    :return:
    """
    try:
        connection = psycopg2.connect(**DATABASE_CONNECTION)
        cursor = connection.cursor()
        cursor.execute(query)
        response = cursor.fetchall()
        cursor.close()
        connection.close()
        return response

    except (Exception, psycopg2.DatabaseError) as error:
        logger.exception(f"Database error: {error}")
        return


def execute_commit(query):
    """
    Commit database
    :param query:
    :return:
    """
    try:
        connection = psycopg2.connect(**DATABASE_CONNECTION)
        cursor = connection.cursor()
        cursor.execute(query)
        connection.commit()
        cursor.close()
        connection.close()
        return True

    except (Exception, psycopg2.DatabaseError) as error:
        logger.exception(f"Database error: {error}")
        return


def execute_count(query):
    """
    Count elements in database
    :param query:
    :return:
    """
    try:
        connection = psycopg2.connect(**DATABASE_CONNECTION)
        cursor = connection.cursor()
        cursor.execute(query)
        if cursor.rowcount:
            cursor.close()
            connection.close()
            return True
        else:
            cursor.close()
            connection.close()
            return False

    except (Exception, psycopg2.DatabaseError) as error:
        logger.exception(f"Database error: {error}")
        return


def check_if_link_exists(store, link):
    """
    Check if link exists
    :param store:
    :param link:
    :return:
    """
    if execute_count(f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}';"):
        return True
    else:
        return False


def check_if_links_deactivated(store, link):
    """
    Check if link is deactivated
    :param store:
    :param link:
    :return:
    """
    if execute_count(f"SELECT DISTINCT link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}' AND visible='no';"):
        return True
    else:
        return False

def delete_manual_links(store, link):
    """
    Delete given link
    :param store:
    :param link:
    :return:
    """
    execute_commit(f"DELETE FROM public.manual_urls WHERE store='{store.lower()}' AND link='{link}';")
    return True


def get_product_id(store, link):
    """
    Get id from database for specific link
    :param store:
    :param link:
    :return:
    """
    product = execute_fetch_all(f"SELECT DISTINCT id, store, link FROM public.store_items WHERE store='{store.lower()}' AND link='{link}' AND visible='yes';")
    return {"id": product(0)(0), "store": product(0)(1), "link": product(0)(2)}

def get_all_links(store):
    """
    Return all links in database
    :param store:
    :return:
    """
    cur = execute_fetch_all(f"SELECT DISTINCT id, link FROM public.store_items WHERE store='{store.lower()}' AND visible='yes';")
    return ({"id": links(0), "link": links(1)} for links in cur)



def check_if_store_exists(store):
    """
    Check if the store exists in database
    :param store:
    :return:
    """
    if execute_count(f"SELECT DISTINCT store FROM public.store_config WHERE store='{store.lower()}';"):
        return True
    else:
        return False


def register_store(store):
    """
    Register the store
    :param store:
    :return:
    """
    if check_if_store_exists(store=store) is False:
        execute_commit(f"INSERT INTO public.store_config (store) VALUES ('{store.lower()}');")
        return True
    else:
        return False

I wonder if there is a way to maybe even short the code by alot or to also improve when using postgres combined with Python since it is new for me still but I do see potential that I might be able to shorter the code quite alot here

If there is any missing information, please let me know in comments and I will try my best to give the information that I might have forgot to add here

Python: Fill a pandas dataframe (of predetermined size) with results from a similar dataframe (of size less than or equivalent to the original)

I’d like some feedback/suggestions on how to improve the following.. Specifically I want to know if what I’m doing is reliable and fast, or if there is a better way to accomplish this.

The problem:

I have some dataset containing counts of sales made at different times throughout the day, across different locations/shops. Let’s say there are 4 different shops contained in this data (A, B, C, D), and there are 4 different time bins in the day (0,1,2,3). I query this and return a query dataset, but the issue I have is that for this query there may be no transactions for a certain time bin. Or there may be no transactions even for a specific shop (maybe there was a rat infestation and it closed for the day). Nevertheless, the end result must have the same number of rows (4 locations x 4 time bins), and simply contain zeros if there were no transactions there. In other words, I want records for all possible occurrences, even if they were not returned by the query itself.

Example:

import pandas as pd

# Specify the complete list of possible time bins
max_timebins = 3
bin_nums = list(range(max_timebins + 1))

# Specify the complete list of shops
shop_ids = ('A', 'B','C','D')

# Make a dataframe for all possible results without the counts
# This is just a dataframe with an index and no columns... this feels a little strange to me but it worked...
dat = {'shop':(), 'timebin':()}
for shop in shop_ids:
    dat('shop')+=(shop)*len(bin_nums)
    dat('timebin') += bin_nums
df_all = pd.DataFrame(dat)
df_all = df_all.set_index(list(dat.keys()))

# Example of a result of a query
dfq = pd.DataFrame(
    {
        'shop':('A', 'A', 'A', 'A',
                'B', 'B',
                'C', 'C', 'C',
                'D'),
        'time_bins':(0,1,2,3,
                     0, 3,
                     0,2,3,
                     2),
        'counts':(100,220, 300, 440,
                  500, 660,
                  120, 340, 90,
                  400)}).set_index(('shop', 'time_bins'))


result_df = pd.concat((df_all, dfq), axis=1).fillna(0).astype(int)