Python Forum
mutable values to string items?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
mutable values to string items?
#11
(Aug-29-2022, 07:33 PM)deanhystad Wrote: Why do you suddenly need a file? Before you had a list that contained this information. Why can't you still use a list (or a dictionary)?
Because i want to use a configuration file that doesn't have to be edited in the file itself since so the software can read the setted channels from its own configuration
Quote:What string are you talking about here?
Quote:The string is like this in the new situation:
limiter_chans.ircnet "#python,#forum"
Like i said in the posts above you can set it in the software like:
/set plugins.var.python.limiter.limiter_chans.ircnet #python,#forum
Quote:What command in your program is returning this string? Or are you trying to generate a string like this?
channels = config_get_plugin('limiter_chans.{}'.format(network))
Also noticed that in the posts and it doesn't matter if it is weechat or not, I'm only asking how to store the data to a file and how to retrieve that back. Does it matter, the software is weechat?As far as i know it is a pyhon question, nothing more.
Reply
#12
Context helps when the question doesn't make any sense (my issue, not yours). I'm still a little fuzzy about this entire thread. But if you do want to save information in a file, and you like Gribouillis' post, I think you will like json even better.

An advantage of json over csv is that there are no intermediate steps required to translate the Python object you want to save to something that can be written to a file. The json dump command does this for you. The same goes in the reverse direction using json load. The result of reading (loading) a json file is a Python object that you can use without any further processing.

Here I translate Gribouillis' csv code to similar code that uses json. I changed the channels datatype from list to dictionary, but json can also read/write a list of lists.
import json
from pathlib import Path
 
source = "plugins.var.python.limiter.limiter_chans.ircnet #python,#forum"
 
# extract the list ['#python', '#forum']
ichan = [x.strip() for x in source.split(' ', 1)[1].strip().split(',')]

# create the dictionary
channels = {x:0 for x in ichan}

# optional: save content to file
filename = Path(__file__).parent/'channels.json'
with open(filename, "w") as file:
    json.dump(channels, file)
 
# optional: read file to get content
with open(filename, "r") as file:
    channels = json.load(channels, file)
 
print(channels) # prints {'#python':0, '#forum':0}
The disadvantage of json is that a csv file is prettier when you print it out. Json files are human readable but look more like html than a table.

I'm still not seeing the reason for a file unless you need some kind of persistence.

I did take a shot at modifying your "new" code to be more like the old. Instead of a static network and list of channels, that information is loaded from configuration information the first time limiter_cb runs. From then on it looks exactly like your old code.
# Simple Channel limiter version 0.1.
# Protection script against mass joining from clones/botnets on your channel.
  
''' /set plugins.var.python.limiter.limiter_chans.ircnet #python,#forum '''
  
from weechat import (
    WEECHAT_RC_OK, register, infolist_get, infolist_string, buffer_search,
    config_get_plugin, infolist_next, string_eval_expression, command, hook_timer, infolist_free)
  
NAME = 'limiter'
AUTHOR = 'fozz <[email protected]>'
VERSION = '0.1'
LICENSE = 'GPL3'
DESCRIPTION = 'Channel limiter, protection against mass joining from clones/botnets'
  
register(NAME, AUTHOR, VERSION, LICENSE, DESCRIPTION, '', '')
  
# Configuration 
limit_ = 5
min_offset_ = 2 #lowest diff
max_offset_ = 2 #highest diff
interval_ = 1
channels_ = []

class Channel:
    def __init__(self, network, channel, offset=0):
        self.network = network
        self.channel = channel
        self.offset = offset

def initialize_channel_list():
    networks = infolist_get('irc_server', '', '')
    while infolist_next(networks):
        network = infolist_string(networks, 'name')
        limiter_chans = config_get_plugin('limiter_chans.{}'.format(network))
        if limiter_chans:
            for channel in limiter_chans.split(','):
                channels_.append(Channel(network, channel))
    infolist_free(networks)

def limiter_cb(data, signal):
    if len(channels_) == 0:
        initialize_channel_list()

    for channel in channels_:
        buffer = buffer_search('irc', '{}.{}'.format(channel.network, channel.channel))
        if buffer:
            nc = int(string_eval_expression('${buffer.nicklist_visible_count}', {'buffer': buffer}, {}, {}))
            nl = nc + limit_ 
            minoff = nl - min_offset_
            maxoff = nl + max_offset_
            if channel.offset <= minoff or channel.offset >= maxoff:
                command(buffer, '/mode ' + channel + ' +l ' + f'{nl}')
                channel.offset = nl  # save value for next time

    return WEECHAT_RC_OK
  
hook_timer(interval_ * 60000, 0, 0, 'limiter_cb', '')
fozz likes this post
Reply
#13
(Aug-30-2022, 05:25 AM)deanhystad Wrote: I'm still not seeing the reason for a file unless you need some kind of persistence.
If I understand well, @fozz needs some persistence, that's why they want to serialize the data.
Reply
#14
The persistence was provided by the networks_ list in the old script. Why a file now? I think the problem is that @fozz has been looking at the problem backward. The question is not "mutable values to string items?" but instead "mutable items from string values?" This question was answered well by many, but it was not enough information for a complete solution because @fozz didn't ask the real question. The real question should have mentioned plugins and getting configuration information and using this information to create a channel list like the one used in the original script. Without that context the early replies only solved how to convert a structured string into a mutable object and skipped the part about when this should be done (only once, at startup).

I certainly could be wrong.
Reply
#15
Yes, exactly were i was looking for deanhystad, the idea for using a file raised up after days of googling and trying some stuff, I didn't realized that it could be done without a file, excuse me for that. I tested your edited script today and it is doing its job.
Probs for all the help, it's all as it should be now! Thank you.
Reply
#16
It is a common mistake on the forum to ask how to implement a solution when you aren't quite sure about the solution. It is always best to start out with "This is the problem I am trying to solve." and then follow that up with "This is what I am trying." and finally "This is how it is failing." Even the most seasoned Python programers start down the wrong path from time to time.

Almost all of my threads contain a response that points to me not describing the real problem well enough.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  using mutable in function defintion as optional paramter akbarza 4 233 Yesterday, 12:52 PM
Last Post: deanhystad
  How to parse and group hierarchical list items from an unindented string in Python? ann23fr 0 203 Mar-27-2024, 01:16 PM
Last Post: ann23fr
  mutable argument in function definition akbarza 1 490 Dec-15-2023, 02:00 PM
Last Post: deanhystad
  Trying to compare string values in an if statement israelsattleen 1 564 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  Getting rid of old string values Pedroski55 3 1,027 Oct-11-2022, 10:56 PM
Last Post: Pedroski55
  Parse String between 2 Delimiters and add as single list items lastyle 5 3,402 Apr-11-2021, 11:03 PM
Last Post: lastyle
  "'DataFrame' objects are mutable, thus they cannot be hashed" Mark17 1 6,841 Dec-25-2020, 02:31 AM
Last Post: tinh
  Mutable Strings millpond 3 2,572 Aug-24-2020, 08:42 AM
Last Post: millpond
  Function parameters and values as string infobound 1 1,770 Jul-24-2020, 04:28 AM
Last Post: scidam
  xml.etree.ElementTree extract string values matthias100 2 4,999 Jul-12-2020, 06:02 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020