Re: What F strings should have been
D'Arcy Cain wrote:
> A recent post by Terry Jan Reedy got me thinking about formatting. I
> like the new(ish) format method for strings and I see some value in F
> strings but it only works well with locals. Anything more starts
> getting messier than format() and it is supposed to be cleaner. Also, I
> find that I tend to re-use format strings and wish there was a
> formatting string option. Here is what I came up with.
>
> class FSTR(str):
> def __call__(self, *args):
> return self.format(*args)
>
> And here is how it could be used.
>
> s = FSTR("ABC {1} {0} {2[x]}")
This can be simplified to
s = "ABC {1} {0} {2[x]}".format
> ...
> print(s(1, 2, dict(x=3)))
>
> Too bad that it is too late to assign f'' to that function.
I must be missing something. How would you simplify or improve the
readability of the above with your version of f"..."?
--
https://mail.python.org/mailman/listinfo/python-list
Re: Old format with %
It can be escaped: "test %d %%" % 7
Terry Reedy schrieb am Mi., 14. Feb. 2018 um 20:53 Uhr:
> On 2/14/2018 7:54 AM, ast wrote:
> > Le 14/02/2018 à 13:46, ast a écrit :
> >> Hello
> >>
> >> It seems that caracter % can't be escaped
> >>
> >> >>>"test %d %" % 7
> >> ValueError: incomplete format
> >>
> >> >>>"test %d \%" % 7
> >> ValueError: incomplete format
> >>
> >> >>>"test %d" % 7 + "%"
> >> 'test 7%' # OK
> >>
> >> But is there a way to escape a % ?
> >>
> >> thx
> >
> > Found, double % to escape it
> >
> > >>>"test %d%%" % 7
> > 'test 7%'
>
> Same with { and } in new format and f strings.
> >>> a = 3
> >>> f'{{x:{a}}}'
> '{x:3}'
>
> --
> Terry Jan Reedy
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
--
https://mail.python.org/mailman/listinfo/python-list
Re: What F strings should have been
On 02/15/18 02:56, Peter Otten wrote:
>> class FSTR(str):
>> def __call__(self, *args):
>> return self.format(*args)
>>
>> And here is how it could be used.
>>
>> s = FSTR("ABC {1} {0} {2[x]}")
>
> This can be simplified to
>
> s = "ABC {1} {0} {2[x]}".format
Hmm. Hadn't thought of that.
>> print(s(1, 2, dict(x=3)))
>>
>> Too bad that it is too late to assign f'' to that function.
>
> I must be missing something. How would you simplify or improve the
> readability of the above with your version of f"..."?
s = f"ABC {1} {0} {2[x]}"
--
D'Arcy J.M. Cain
Vybe Networks Inc.
http://www.VybeNetworks.com/
IM:[email protected] VoIP: sip:[email protected]
--
https://mail.python.org/mailman/listinfo/python-list
Getting "ValueError: need more than 1 value to unpack" while trying to read a value from dictionary in python
Below is my code. Here I want to read the "ip address" from s
s= '''
Power On Enabled = On
State: connected
Radio Module: Unknown
noise: -097
signalStrength: -046
ip address: 192.168.75.147
subnet mask: 255.255.255.0
IPv4 address configured by DHCP
Mac Addr: ac:e2:d3:32:00:5a
Mode: infrastrastructure
ssid: Cloudlab
Channel: 1
Regulatory: World Safe
Authencation: WPA2/PSK
Encryption: AES or TKIP
'''
s = s.replace("=",":")
# s = s.strip()
print s
d = {}
for i in s:
key, val = i.split(":")
d[key] = val.strip()
print d
print d["ip address"]
Getting below error :
key, val = i.split(":")
ValueError: need more than 1 value to unpack
--
https://mail.python.org/mailman/listinfo/python-list
Re: Getting "ValueError: need more than 1 value to unpack" while trying to read a value from dictionary in python
IPv4 address configured by DHCP
It doesn't find key and value for above string.
Solution.. Use one complete string per line
On 15 Feb 2018 4:41 pm, "Sum J" wrote:
Below is my code. Here I want to read the "ip address" from s
s= '''
Power On Enabled = On
State: connected
Radio Module: Unknown
noise: -097
signalStrength: -046
ip address: 192.168.75.147
subnet mask: 255.255.255.0
IPv4 address configured by DHCP
Mac Addr: ac:e2:d3:32:00:5a
Mode: infrastrastructure
ssid: Cloudlab
Channel: 1
Regulatory: World Safe
Authencation: WPA2/PSK
Encryption: AES or TKIP
'''
s = s.replace("=",":")
# s = s.strip()
print s
d = {}
for i in s:
key, val = i.split(":")
d[key] = val.strip()
print d
print d["ip address"]
Getting below error :
key, val = i.split(":")
ValueError: need more than 1 value to unpack
--
https://mail.python.org/mailman/listinfo/python-list
--
https://mail.python.org/mailman/listinfo/python-list
Re: Getting "ValueError: need more than 1 value to unpack" while trying to read a value from dictionary in python
On 15 February 2018 at 12:07, Sum J wrote:
> Below is my code. Here I want to read the "ip address" from s
>
>
> s= '''
> Power On Enabled = On
> State: connected
> Radio Module: Unknown
> noise: -097
> signalStrength: -046
> ip address: 192.168.75.147
> subnet mask: 255.255.255.0
> IPv4 address configured by DHCP
> Mac Addr: ac:e2:d3:32:00:5a
> Mode: infrastrastructure
> ssid: Cloudlab
> Channel: 1
> Regulatory: World Safe
> Authencation: WPA2/PSK
> Encryption: AES or TKIP
> '''
>
>s = s.replace("=",":")
># s = s.strip()
>print s
>
> d = {}
> for i in s:
> key, val = i.split(":")
> d[key] = val.strip()
>
> print d
> print d["ip address"]
>
>
> Getting below error :
> key, val = i.split(":")
> ValueError: need more than 1 value to unpack
> --
> https://mail.python.org/mailman/listinfo/python-list
If you iterate over a string, you are iterating over individual
characters. Instead, you need to split it into lines, first stripping
whitespace (starts and ends with an empty line).
s = s.strip().replace("=",":")
print s
d = {}
for i in s.split('\n'):
try:
key, val = i.split(":")
d[key.strip()] = val.strip()
except ValueError:
print "no key:value pair found in", i
(PS. please switch to Python 3)
--
Chris Warrick
PGP: 5EAAEA16
--
https://mail.python.org/mailman/listinfo/python-list
"Programs" folder not found.
Hello! So I downloaded “Python” program in C:>Users>(my name)>AppData>Local>Programs>Python.And then in “Local” folder I can’t find “Programs” folder,but it says it downloaded in “Programs”.So can you help me. -- https://mail.python.org/mailman/listinfo/python-list
Python GIL vs CAS
Hi. While hearing about GIL every time... is there any real reason why CAS doesn't help to solve this problem? https://en.wikipedia.org/wiki/Compare-and-swap -- https://mail.python.org/mailman/listinfo/python-list
Re: Regex on a Dictionary
Hello, this question also came up there: https://python-forum.io/Thread-Working-with-Dict-Object Greetings Andre -- https://mail.python.org/mailman/listinfo/python-list
Re: Python GIL vs CAS
On Thu, Feb 15, 2018 at 2:40 PM, Oleg Korsak wrote: > Hi. While hearing about GIL every time... is there any real reason why CAS > doesn't help to solve this problem? > > https://en.wikipedia.org/wiki/Compare-and-swap Because the GIL is not a problem. It's a feature. Before you ask about solutions, you need to clarify what you are calling a problem :) ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: "Programs" folder not found.
Look in %localappdata%\Programs\Python Enerel Amgalan via Python-list schrieb am Do., 15. Feb. 2018 um 14:05 Uhr: > > Hello! So I downloaded “Python” program in C:>Users>(my > name)>AppData>Local>Programs>Python.And then in “Local” folder I can’t find > “Programs” folder,but it says it downloaded in “Programs”.So can you help > me. > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
How to benchmark a HTTP connection with requests module?
Hi, Is it possible to emulate a range of concurrent connections to a http server with the requests module? import os import requests from test_support import unittest class HTTPBenchmarkTestCase(unittest.TestCase): url = 'http://localhost/benchmark/' def setUp(self): pass def test_benchmark_concurrency(self): # XXX it would be really nice to execute 10 concurrent requests # with 10 separated threads/connections. r = requests.get(self.url) self.assertEqual(r.status_code, 200) def tearDown(self): pass def runTest(self): pass What do you think? Etienne -- https://mail.python.org/mailman/listinfo/python-list
Re: Python GIL vs CAS
On 2/15/18 9:35 AM, Chris Angelico wrote: On Thu, Feb 15, 2018 at 2:40 PM, Oleg Korsak wrote: Hi. While hearing about GIL every time... is there any real reason why CAS doesn't help to solve this problem? https://en.wikipedia.org/wiki/Compare-and-swap Because the GIL is not a problem. It's a feature. Before you ask about solutions, you need to clarify what you are calling a problem :) Let's not overstate the case. The GIL is not a feature, it's an effective solution to a problem. The Python interpreter has data that is shared among threads, including the state of the interpreter, and all of the reference counts of all of the Python objects. When that data is modified, it must be done in a thread-safe way. The GIL is a simple and effective solution to doing that correctly. Oleg, CAS is a processor primitive that can be used to implement synchronization tools, including locks like the GIL. You can't replace the GIL with CAS, since they are not equivalent. You'll need to flesh out your idea about how CAS can help solve the "mutating shared interpreter state" problem that the GIL solves. --Ned. -- https://mail.python.org/mailman/listinfo/python-list
Re: What F strings should have been
On Wed, Feb 14, 2018 at 2:24 PM, D'Arcy Cain wrote:
> A recent post by Terry Jan Reedy got me thinking about formatting. I
> like the new(ish) format method for strings and I see some value in F
> strings but it only works well with locals. Anything more starts
> getting messier than format() and it is supposed to be cleaner. Also, I
> find that I tend to re-use format strings and wish there was a
> formatting string option. Here is what I came up with.
>
> class FSTR(str):
> def __call__(self, *args):
> return self.format(*args)
>
> And here is how it could be used.
>
> s = FSTR("ABC {1} {0} {2[x]}")
> ...
> print(s(1, 2, dict(x=3)))
>
> Too bad that it is too late to assign f'' to that function.
Someday far in the future Python will be remembered as a language that
people in the before-time used to format strings.
--
https://mail.python.org/mailman/listinfo/python-list
Re: Python GIL vs CAS
On Fri, Feb 16, 2018 at 3:27 AM, Ned Batchelder wrote: > On 2/15/18 9:35 AM, Chris Angelico wrote: >> >> On Thu, Feb 15, 2018 at 2:40 PM, Oleg Korsak >> wrote: >>> >>> Hi. While hearing about GIL every time... is there any real reason why >>> CAS >>> doesn't help to solve this problem? >>> >>> https://en.wikipedia.org/wiki/Compare-and-swap >> >> Because the GIL is not a problem. It's a feature. Before you ask about >> solutions, you need to clarify what you are calling a problem :) >> > > Let's not overstate the case. The GIL is not a feature, it's an effective > solution to a problem. The Python interpreter has data that is shared among > threads, including the state of the interpreter, and all of the reference > counts of all of the Python objects. When that data is modified, it must be > done in a thread-safe way. The GIL is a simple and effective solution to > doing that correctly. Okay, I kinda exaggerated. But the GIL isn't a "problem". As you say, it's a simple way to achieve an important goal. Removing the GIL from CPython *has* been done, more than once. Each time, the alternative gave some performance improvements, and a number of penalties. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Getting "ValueError: need more than 1 value to unpack" while trying to read a value from dictionary in python
Thanks Chris :)
Its working now.
Regards,
Sumit
On Thu, Feb 15, 2018 at 4:55 PM, Chris Warrick wrote:
> On 15 February 2018 at 12:07, Sum J wrote:
> > Below is my code. Here I want to read the "ip address" from s
> >
> >
> > s= '''
> > Power On Enabled = On
> > State: connected
> > Radio Module: Unknown
> > noise: -097
> > signalStrength: -046
> > ip address: 192.168.75.147
> > subnet mask: 255.255.255.0
> > IPv4 address configured by DHCP
> > Mac Addr: ac:e2:d3:32:00:5a
> > Mode: infrastrastructure
> > ssid: Cloudlab
> > Channel: 1
> > Regulatory: World Safe
> > Authencation: WPA2/PSK
> > Encryption: AES or TKIP
> > '''
> >
> >s = s.replace("=",":")
> ># s = s.strip()
> >print s
> >
> > d = {}
> > for i in s:
> > key, val = i.split(":")
> > d[key] = val.strip()
> >
> > print d
> > print d["ip address"]
> >
> >
> > Getting below error :
> > key, val = i.split(":")
> > ValueError: need more than 1 value to unpack
> > --
> > https://mail.python.org/mailman/listinfo/python-list
>
> If you iterate over a string, you are iterating over individual
> characters. Instead, you need to split it into lines, first stripping
> whitespace (starts and ends with an empty line).
>
> s = s.strip().replace("=",":")
> print s
>
> d = {}
> for i in s.split('\n'):
> try:
> key, val = i.split(":")
> d[key.strip()] = val.strip()
> except ValueError:
> print "no key:value pair found in", i
>
>
> (PS. please switch to Python 3)
>
> --
> Chris Warrick
> PGP: 5EAAEA16
>
--
https://mail.python.org/mailman/listinfo/python-list
Re: Getting "ValueError: need more than 1 value to unpack" while trying to read a value from dictionary in python
On 2018-02-15 11:25, Chris Warrick wrote:
On 15 February 2018 at 12:07, Sum J wrote:
Below is my code. Here I want to read the "ip address" from s
s= '''
Power On Enabled = On
State: connected
Radio Module: Unknown
noise: -097
signalStrength: -046
ip address: 192.168.75.147
subnet mask: 255.255.255.0
IPv4 address configured by DHCP
Mac Addr: ac:e2:d3:32:00:5a
Mode: infrastrastructure
ssid: Cloudlab
Channel: 1
Regulatory: World Safe
Authencation: WPA2/PSK
Encryption: AES or TKIP
'''
s = s.replace("=",":")
# s = s.strip()
print s
d = {}
for i in s:
key, val = i.split(":")
d[key] = val.strip()
print d
print d["ip address"]
Getting below error :
key, val = i.split(":")
ValueError: need more than 1 value to unpack
--
https://mail.python.org/mailman/listinfo/python-list
If you iterate over a string, you are iterating over individual
characters. Instead, you need to split it into lines, first stripping
whitespace (starts and ends with an empty line).
s = s.strip().replace("=",":")
print s
d = {}
I'd use .splitlines instead:
for i in s.split('\n'):
try:
.partition works better here. You should note that the "Mac Addr" line
has multiple colons, most of which are part of the value!
key, val = i.split(":")
d[key.strip()] = val.strip()
except ValueError:
print "no key:value pair found in", i
s = s.replace("=",":")
d = {}
for line in s.splitlines():
key, sep, val = line.partition(":")
if sep:
d[key.strip()] = val.strip()
else:
print "no key:value pair found in", line
>
> (PS. please switch to Python 3)
> +1
--
https://mail.python.org/mailman/listinfo/python-list
Re: Suggestions on programming in Python an email simple client
Il giorno martedì 13 febbraio 2018 21:06:19 UTC+1, Maroso Marco ha scritto: > Hi, > > what i'm trying to do is develop my own email client, but a simple one. > > I just want it to connect to a specific email account and read the subject > line of messages coming from a certain email address. > > I then want it to be able to execute the command i wrote on the subject. > > It would be nice if i could specify two parameters on the subject line > > first : password; > second : command; > > The first parameter is the password and the second is the command to be > executed in the local pc where this program is running. > > The program will have to show only email coming from a specific account > and if the mail is unread then it should read the subject line and find > parameters. > The first parameter must match my hardcoded password, and the second > parameter must be executed on the local pc (example ... > c:\windows\notepad.exe) > > It must check for new emails at a given timing (example ...every 30 seconds ) > (the timing can be hardcoded or specified in a separate file) > > This is it. > > Any suggestions? > > I have started doing this (but i never programmed in python before): > > > import imaplib > import os > import email > import email.header > > plusmail = "[email protected]" > googlepass = "mypassword" > owner = "[email protected]" > > M = imaplib.IMAP4_SSL('imap.gmail.com') > M.login(plusmail, googlepass) > M.select() > > status, response = M.search(None, '(UNSEEN)') > unread_msg_nums = response[0].split() > > # Print the count of all unread messages > print (len(unread_msg_nums)) > > # Print all unread messages from a certain sender of interest > status, response = M.search(None, '(UNSEEN)', '(FROM "%s")' % (owner)) > unread_msg_nums = response[0].split() > da = [] > for e_id in unread_msg_nums: > _, response = imap.fetch(e_id, '(BODY.PEEK[HEADER.FIELDS (From Subject)] > RFC822.SIZE)') > da.append(response[0][1]) > # print (da) > > # Mark them as seen > for e_id in unread_msg_nums: > imap.store(e_id, '+FLAGS', '\Seen') > > > > typ, data = M.search(None, 'From',(owner)) > for num in data[0].split(): > typ, data = M.fetch(num, '(RFC822)') > print ('Message %s\n%s\n' % (num, data[0][1])) > M.close() > M.logout() > > I know there are duplicates but i need to figure out how to build this > correctly > > > Thanks in advance for any help given. OK, i came up to this solution, but now i tried to compile and run as a service, but it doesnt seem to work, not fetching emails and reading comand. # A SCRIPT FROM MININGFELLOWS By CrazyLion import imaplib import os import email import email.header import time import subprocess def mailcontroller(): # Set user, pass and allowed mail for giving commands plusmail = "mailmailaddress.com" googlepass = "thepassword" captain = "[email protected]" # Set vars for IMAP access M = imaplib.IMAP4_SSL('imap.gmail.com') M.login(plusmail, googlepass) M.select() # Set search on UNSEEN messages status, response = M.search(None, '(UNSEEN)') unread_msg_nums = response[0].split() # Mark as read for e_id in unread_msg_nums: M.store(e_id, '+FLAGS', '\Seen') # cycle messages sent from autorized email address typ, data = M.search(None, 'From',(captain)) for num in data[0].split(): typ, data = M.fetch(num, '(RFC822)') msg = email.message_from_string(data[0][1]) decode = email.header.decode_header(msg['Subject'])[0] subject = unicode(decode[0]) comando = subject if googlepass in subject: # print 'Message %s: %s' % (num, subject) # Split subject line googlepass,comando = subject.split(";") # Execute command #os.system(comando) # Execute command with alternate method subprocess.call(comando) # Delete email M.store(num, '+FLAGS', '\\Deleted') M.close() M.logout() # Read ini file for timer settings timing = open('timing.ini', 'r').read() # Convert timer value from string to int time.sleep(int(timing)) while True: mailcontroller() Any suggestions on how to compile it to run as a service. I've tried to compile it in 32 and 64 bit version. 32 bit version runs ok, the 64 shuts after some seconds. How to run comands like "net stop spooler" or "notepad" or "c:\file.bat" but as administrator (i mean with admin rights) Tried to create a service based on my compiled version, it is in the processes but it does not do anything. Thanks really. -- https://mail.python.org/mailman/listinfo/python-list
Re: Suggestions on programming in Python an email simple client
On 2018-02-15 16:30, Maroso Marco wrote: Il giorno martedì 13 febbraio 2018 21:06:19 UTC+1, Maroso Marco ha scritto: Hi, what i'm trying to do is develop my own email client, but a simple one. I just want it to connect to a specific email account and read the subject line of messages coming from a certain email address. I then want it to be able to execute the command i wrote on the subject. It would be nice if i could specify two parameters on the subject line first : password; second : command; The first parameter is the password and the second is the command to be executed in the local pc where this program is running. You should never write anything that requires or even allows providing a password on a command line. On any multiuser machine, somebody can look for processes that have your program as the command and see the password. Passwords should only ever be provided interactively -- Michael F. Stemper Soglin for governor. -- https://mail.python.org/mailman/listinfo/python-list
