[Tutor] Regex for Filesystem path
Hi all , Can you provide some advice and code for the following problem : I have a logfile to check for errors : /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' ) st1 = f3.readlines () from the above log I extract the directory location to determine the location of another log using the following regular expresssion: for j in range ( len ( st1 ) ): patchnumber = re.compile(r'(\d+)\/(\d+)') mo = patchnumber.search (st1[j-1]) a = mo.group() ## 123456/789 === How to do I traverse to the required directory which is /a/b/c/d/test/123456/789 ? 1) First I need to extract /a/b/c/d/test/ from /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log ? 2) Then add 123456/789 and create directory location as /a/b/c/d/test/123456/789 3) cd /a/b/c/d/test/123456/789 4) look for the latest file in the directory /a/b/c/d/test/123456/789 5) print its content Please advice , -- Asad Hasan +91 9582111698 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python
Dear Python Experts Team, As am newbie to python development, I am trying to use the below function to get verify the filesystem type of the SD card parition using bash command in python using subprocess module, I ma seeing the below Error "SyntaxError: can't assign to literal" *CODE:* ** import helper from os import path import subprocess import os import otg_ni class emmc(object): """ emmc getters and setters info: https://www.kernel.org/doc/Documentation/cpu-freq/user-guide.txt """ def __init__(self): self._helper = helper.helper() self._otg_ni = otg_ni.otg_ni() *def get_fstype_of_mounted_partition(self, fs):* """ Get the filesystem type of the mounted partition. :partition_name : Partition path as string (e.g. /dev/mmcblk0p1) :return: filesystem type as string or None if not found """ *cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* *return self._helper.execute_cmd_output_string(cmd)* *def execute_cmd_output_string(self, cmd, enable_shell=False):* """ Execute a command and return its output as a string. :param cmd: abs path of the command with arguments :param enable_shell : force the cmd to be run as shell script :return: a string. """ try: result = subprocess.check_output(split(cmd), stderr=subprocess.STDOUT, shell=enable_shell) except subprocess.CalledProcessError as e: s = """While executing '{}' something went wrong. Return code == '{}' Return output:\n'{}' """.format(cmd, e.returncode, e.output, shell=enable_shell) raise AssertionError(s) return result.strip().decode("utf-8") *if __name__ == "__main__":* m = emmc() *m.get_fstype_of_mounted_partition("/dev/mmcblk0p1")* *Error:* *==* root:~/qa/test_library# python3 sd.py File "sd.py", line 99 *cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* * ^* *SyntaxError: can't assign to literal* root:~/qa/test_library# Kindly do the needful as early as possible, as am stuck with this issue from past 2 days no clues yet, please redirect me to the correct forum if this is not the right place for pasting python related queries Many Thanks in advance, Srini ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex for Filesystem path
On 06/11/2018 13:13, Asad wrote: > Can you provide some advice and code for the following problem : The first thing is to go read the documentation for the os.path module. It is designed for reliable path manipulation. > /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log > > f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' ) > st1 = f3.readlines () You hardly ever need readlines() any more, just iterate over the file, its much easier. > for j in range ( len ( st1 ) ): for line in f3: >patchnumber = re.compile(r'(\d+)\/(\d+)') > >mo = patchnumber.search (st1[j-1]) Are you sure that's right? For the first index (0) stl[j-1] will be stl[-1] which is the last line in the file. >a = mo.group() ## 123456/789 >=== >How to do I traverse to the required directory which is > /a/b/c/d/test/123456/789 ? You can use relative paths in os.chdir. So a payth of '..' will be one level up from the current directory. Of course you need to chdir to that directory first but os.path will tell you the dir you need. Or if its a hard coded path just store the /a/b/c/d/test/ in a variable. But I'm guessing that's too obvious so the path may vary? >1) First I need to extract /a/b/c/d/test/ from > /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log ? get the dir then chdir to .. from there. >2) Then add 123456/789 and create directory location as > /a/b/c/d/test/123456/789 Simple string manipulation or use the os.path functions. >3) cd /a/b/c/d/test/123456/789 os.chdir() >4) look for the latest file in the directory /a/b/c/d/test/123456/789 Slightly more complex, you need the creation timestamp. You can find that with os.path.getctime() (or several other options, eg os.stat) >5) print its content standard file processing hth -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python
> > *def get_fstype_of_mounted_partition(self, fs):* >""" >Get the filesystem type of the mounted partition. > >:partition_name : Partition path as string (e.g. /dev/mmcblk0p1) >:return: filesystem type as string or None if not found >""" > > *cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* >*return self._helper.execute_cmd_output_string(cmd)* > > > > root:~/qa/test_library# python3 sd.py > File "sd.py", line 99 > *cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* > * ^* > *SyntaxError: can't assign to literal* > root:~/qa/test_library# > looking at cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* It’s probably because you have “ characters that are inside “ characters and it can’t tell where the string ends. It looks like you are trying to do cmd = "blkid -o export %s | grep 'TYPE' | cut -d” = " -f3" % (fs)* which doesn’t make sense. Try using triple quotes instead so it’s clear what string you are trying to use. cmd = “""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3”"" % (fs) — David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex for Filesystem path
>>4) look for the latest file in the directory /a/b/c/d/test/123456/789 > > Slightly more complex, you need the creation timestamp. > You can find that with os.path.getctime() (or several > other options, eg os.stat) here's a trick you might be able to make use of: somelist = generate-list-of-files-in-directory newest = max(somelist, key=os.path.getctime) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex for Filesystem path
On 06Nov2018 18:10, Alan Gauld wrote: >On 06/11/2018 13:13, Asad wrote: > >> Can you provide some advice and code for the following problem : > >The first thing is to go read the documentation for the os.path module. >It is designed for reliable path manipulation. > >> /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log >> >> f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' ) >> st1 = f3.readlines () > >You hardly ever need readlines() any more, just iterate >over the file, its much easier. > >> for j in range ( len ( st1 ) ): > >for line in f3: Not to mention cheaper in memory usage. [...snip...] >>a = mo.group() ## 123456/789 >>=== >>How to do I traverse to the required directory which is >> /a/b/c/d/test/123456/789 ? > >You can use relative paths in os.chdir. >So a payth of '..' will be one level up from the current >directory. Of course you need to chdir to that directory first >but os.path will tell you the dir you need. It is better to just construct the required path. Chdir there requires a chdir back, and chdir affects all the relative paths your programme may be using. I'd use os.path.dirname to get '/a/b/c/d/test' and then just append to it with os.path.join to contruct each directory path. [...] >But I'm guessing that's too obvious so the path may vary? >>1) First I need to extract /a/b/c/d/test/ from >> /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log ? Use os.path.dirname: # up the top from os.path import dirname, join # later testdir = dirname(logfile_path) >get the dir then chdir to .. from there. > >>2) Then add 123456/789 and create directory location as >> /a/b/c/d/test/123456/789 > >Simple string manipulation or use the os.path functions. Eg dirpath = join(testdir, '123456/789') >>3) cd /a/b/c/d/test/123456/789 > >os.chdir() I still recommend avoiding this. Just construct the full path to what you need. >>4) look for the latest file in the directory /a/b/c/d/test/123456/789 > >Slightly more complex, you need the creation timestamp. >You can find that with os.path.getctime() (or several >other options, eg os.stat) Do not use ctime, it is _not_ "creation" time. It is "last change to inode" time. It _starts_ as creation time, but a chmod or even a link/unlink can change it: anything that changes the metadata. Generally people want mtime (last nmodified time), which is the last time the file data got changed. It is more meaningful. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Request for help with code
I'm using the bookazine "The Python Book" First Edition on pages 13-14 it gives the code (listed further below). It asks for user to state a given number of integers (for example 4)...then user enters integers. It doesn't stop seeking input after the number requested thereby creating an infinite loop. - CODE - # Python Book Page_13.py # Joe G. # several comment lines explain the code below it. # Re-typing is good practice # We're going to write a program that will ask the user to input an arbitrary # number of intergers, store them in a collection, and then demonstrate how the # collection would be used in various control structures. # Used for the sys.exit function import sys # Requests number of intergers target_int=raw_input("How many intergers?") # By now, the variable target_int contains a string representtion of # whatever the user typed. We need to try and convert that to an interger but # be ready to # deal with the error if it's not. Otherwise the program will # crash # Begin the error check try: target_int=int(target_int) except ValueError: sys.exit("You must enter an interger") # creates a collection (list) called ints ints=list() # keeps track of number of intergers count=0 # Keep asking for an interger until we have the required number while counthttps://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On Nov 6, 2018 4:51 PM, "Joseph Gulizia" wrote: > > I'm using the bookazine "The Python Book" First Edition on pages 13-14 it > gives the code (listed further below). > > It asks for user to state a given number of integers (for example 4)...then > user enters integers. It doesn't stop seeking input after the number > requested thereby creating an infinite loop. > > - > CODE > - > > # Python Book Page_13.py > # Joe G. > > # several comment lines explain the code below it. > # Re-typing is good practice > > # We're going to write a program that will ask the user to input an > arbitrary > # number of intergers, store them in a collection, and then demonstrate how > the > # collection would be used in various control structures. > > # Used for the sys.exit function > import sys > # Requests number of intergers > target_int=raw_input("How many intergers?") > # By now, the variable target_int contains a string representtion of > # whatever the user typed. We need to try and convert that to an interger > but > # be ready to # deal with the error if it's not. Otherwise the program will > # crash > # Begin the error check > try: > target_int=int(target_int) > except ValueError: > sys.exit("You must enter an interger") > # creates a collection (list) called ints > ints=list() > # keeps track of number of intergers > count=0 > # Keep asking for an interger until we have the required number > while count new_int=raw_input("Please enter interger{0}:".format(count+1)) > isint=False > try: > new_int=int(new_int) > except: > print("You must enter an interger") > # Only carry on if we have an interger. If not, we'll loop again > # Notice below I use == which is different from =. The single equals sign > is an > # assignment operator whereas the double equals sign is a comparison > operator. I would > # call it a married eguals signbut whenever single is mentioned I have > to mention marriage. > > if isint==True: > # Add the interger to the collection > ints.append(new_int) > # Increment the count by 1 > count+=1 > # print statement ("using a for loop") > print("Using a for loop") > for value in ints: > print(str(value)) > # Or with a while loop: > print("Using a while loop") > # We already have the total above, but knowing the len function is very > # useful. > total = len(ints) > count = 0 > while count < total: >print(str(ints[count])) >count +=1 > > count = 0 > while count < total: > print(str(ints[count])) > count += 1 > > --- > END OF CODE > --- > Sample output: > > How many integers?3 > Please enter integer1:1 > Please enter integer1:2 > Please enter integer1:3 > Please enter integer1:a > You must enter an integer > Please enter integer1:4 > Please enter integer1:5 > Please enter integer1:6 > Please enter integer1:b > You must enter an integer > Please enter integer1: > (Keeps Looping) > > Thanks in advance Your code came through with all of the indentation removed. Please be sure to send plain text. We could guess at the indentation but we might get it wrong. With the indentation corrected the code you supplied does not agree with the execution. Note the difference between integer and interger. You also did not make any request. Please in the future tell us what you want from us. The fact that the program keeps asking for integer 1 suggest that count is not being incremented. This would also explain why the loop never ends. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On Tue, Nov 06, 2018 at 03:50:42PM -0600, Joseph Gulizia wrote: > I'm using the bookazine "The Python Book" First Edition on pages 13-14 it > gives the code (listed further below). > > It asks for user to state a given number of integers (for example 4)...then > user enters integers. It doesn't stop seeking input after the number > requested thereby creating an infinite loop. The first and most important rule for asking for help with code is to always post plain, unformatted text, not "Rich Text" (formatted text, styled text). Don't add colours, highlighting, bold, italic, fancy fonts, dancing paperclips or anything else, because when you do, it destroys the necessary indentation of the code and makes it impossible to run or debug. For example, your code shows up like this: # Begin the error check try: target_int=int(target_int) except ValueError: sys.exit("You must enter an interger") In that case, we could(?) guess the correct indentation, but (1) sometimes we can't, and (2) we shouldn't have to. The *second* most important rule for posting code is to *keep it simple*. We're volunteers, not slaves, and you should always ask first before posting masses of code for us to investigate. Anything more than, oh, say, thirty lines (including comments) counts as masses. Please try reading this: http://sscce.org/ it is written for Java programmers but the advice applies as well here. Before posting your entire code, take the time to simplify it to a *mimimal example* which demonstrates the same problem. Half the time this will allow you to solve the problem yourself, and the other half of the time, it makes it easier on us slaves! I mean volunteers. At a *guess*, and this is purely a guess because the lack of indentation makes it impossible to understand the structure of your code, I think the infinite loop is probably intentional. If you guess wrongly, it asks you to guess again, *forever*, until you guess correctly. But as I said, I can't really tell. -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
Apologies for earlier errors when asking for help -- I am hopeful that this shortened post displays properly: The code is Python 2... trying to solve why loop doesn't stop at given number of integersif I input request for 3 integersit keeps asking for integer1...and keeps asking for input,,,so count isn't workingtrying to figure out why. Pointers please. import sys target_int=raw_input("How many integers?") try: target_int=int(target_int) except ValueError: sys.exit("You must enter an integer") # creates a collection (list) called ints ints=list() # keeps track of number of integers count=0 # Keep asking for an integer until we have the required number while count wrote: > I'm using the bookazine "The Python Book" First Edition on pages 13-14 it > gives the code (listed further below). > > It asks for user to state a given number of integers (for example > 4)...then user enters integers. It doesn't stop seeking input after the > number requested thereby creating an infinite loop. > > - > CODE > - > > # Python Book Page_13.py > # Joe G. > > # several comment lines explain the code below it. > # Re-typing is good practice > > # We're going to write a program that will ask the user to input an > arbitrary > # number of intergers, store them in a collection, and then demonstrate > how the > # collection would be used in various control structures. > > # Used for the sys.exit function > import sys > # Requests number of intergers > target_int=raw_input("How many intergers?") > # By now, the variable target_int contains a string representtion of > # whatever the user typed. We need to try and convert that to an interger > but > # be ready to # deal with the error if it's not. Otherwise the program > will > # crash > # Begin the error check > try: > target_int=int(target_int) > except ValueError: > sys.exit("You must enter an interger") > # creates a collection (list) called ints > ints=list() > # keeps track of number of intergers > count=0 > # Keep asking for an interger until we have the required number > while count new_int=raw_input("Please enter interger{0}:".format(count+1)) > isint=False > try: > new_int=int(new_int) > except: > print("You must enter an interger") > # Only carry on if we have an interger. If not, we'll loop again > # Notice below I use == which is different from =. The single equals sign > is an > # assignment operator whereas the double equals sign is a comparison > operator. I would > # call it a married eguals signbut whenever single is mentioned I have > to mention marriage. > > if isint==True: > # Add the interger to the collection > ints.append(new_int) > # Increment the count by 1 > count+=1 > # print statement ("using a for loop") > print("Using a for loop") > for value in ints: > print(str(value)) > # Or with a while loop: > print("Using a while loop") > # We already have the total above, but knowing the len function is very > # useful. > total = len(ints) > count = 0 > while count < total: >print(str(ints[count])) >count +=1 > > count = 0 > while count < total: > print(str(ints[count])) > count += 1 > > --- > END OF CODE > --- > Sample output: > > How many integers?3 > Please enter integer1:1 > Please enter integer1:2 > Please enter integer1:3 > Please enter integer1:a > You must enter an integer > Please enter integer1:4 > Please enter integer1:5 > Please enter integer1:6 > Please enter integer1:b > You must enter an integer > Please enter integer1: > (Keeps Looping) > > Thanks in advance > Joe > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On Tue, Nov 6, 2018 at 6:17 PM Joseph Gulizia wrote: > > Apologies for earlier errors when asking for help -- I am hopeful that this > shortened post displays properly: > The code is Python 2... trying to solve why loop doesn't stop at given > number of integersif I input request for 3 integersit keeps asking > for integer1...and keeps asking for input,,,so count isn't > workingtrying to figure out why. Pointers please. > > import sys > > target_int=raw_input("How many integers?") > > try: > target_int=int(target_int) > except ValueError: > sys.exit("You must enter an integer") > > # creates a collection (list) called ints > > ints=list() > > # keeps track of number of integers > > count=0 > > # Keep asking for an integer until we have the required number > > while count new_int=raw_input("Please enter integer{0}:".format(count+1)) > isint=False > try: > new_int=int(new_int) > except: > print("You must enter an integer") > - > > > On Tue, Nov 6, 2018 at 3:50 PM Joseph Gulizia > wrote: > > > I'm using the bookazine "The Python Book" First Edition on pages 13-14 it > > gives the code (listed further below). > > > > It asks for user to state a given number of integers (for example > > 4)...then user enters integers. It doesn't stop seeking input after the > > number requested thereby creating an infinite loop. > > > > - > > CODE > > - > > > > # Python Book Page_13.py > > # Joe G. > > > > # several comment lines explain the code below it. > > # Re-typing is good practice > > > > # We're going to write a program that will ask the user to input an > > arbitrary > > # number of intergers, store them in a collection, and then demonstrate > > how the > > # collection would be used in various control structures. > > > > # Used for the sys.exit function > > import sys > > # Requests number of intergers > > target_int=raw_input("How many intergers?") > > # By now, the variable target_int contains a string representtion of > > # whatever the user typed. We need to try and convert that to an interger > > but > > # be ready to # deal with the error if it's not. Otherwise the program > > will > > # crash > > # Begin the error check > > try: > > target_int=int(target_int) > > except ValueError: > > sys.exit("You must enter an interger") > > # creates a collection (list) called ints > > ints=list() > > # keeps track of number of intergers > > count=0 > > # Keep asking for an interger until we have the required number > > while count > new_int=raw_input("Please enter interger{0}:".format(count+1)) > > isint=False > > try: > > new_int=int(new_int) > > except: > > print("You must enter an interger") > > # Only carry on if we have an interger. If not, we'll loop again > > # Notice below I use == which is different from =. The single equals sign > > is an > > # assignment operator whereas the double equals sign is a comparison > > operator. I would > > # call it a married eguals signbut whenever single is mentioned I have > > to mention marriage. > > > > if isint==True: > > # Add the interger to the collection > > ints.append(new_int) > > # Increment the count by 1 > > count+=1 > > # print statement ("using a for loop") > > print("Using a for loop") > > for value in ints: > > print(str(value)) > > # Or with a while loop: > > print("Using a while loop") > > # We already have the total above, but knowing the len function is very > > # useful. > > total = len(ints) > > count = 0 > > while count < total: > >print(str(ints[count])) > >count +=1 > > > > count = 0 > > while count < total: > > print(str(ints[count])) > > count += 1 > > > > --- > > END OF CODE > > --- > > Sample output: > > > > How many integers?3 > > Please enter integer1:1 > > Please enter integer1:2 > > Please enter integer1:3 > > Please enter integer1:a > > You must enter an integer > > Please enter integer1:4 > > Please enter integer1:5 > > Please enter integer1:6 > > Please enter integer1:b > > You must enter an integer > > Please enter integer1: > > (Keeps Looping) > > > > Thanks in advance > > Joe > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor still not indented.. sorry.. figure that out -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
Funny using a text editorand showed indented in my browser. Won't bother the list again. On Tue, Nov 6, 2018, 17:32 Joel Goldstick On Tue, Nov 6, 2018 at 6:17 PM Joseph Gulizia > wrote: > > > > Apologies for earlier errors when asking for help -- I am hopeful that > this > > shortened post displays properly: > > The code is Python 2... trying to solve why loop doesn't stop at given > > number of integersif I input request for 3 integersit keeps > asking > > for integer1...and keeps asking for input,,,so count isn't > > workingtrying to figure out why. Pointers please. > > > > import sys > > > > target_int=raw_input("How many integers?") > > > > try: > > target_int=int(target_int) > > except ValueError: > > sys.exit("You must enter an integer") > > > > # creates a collection (list) called ints > > > > ints=list() > > > > # keeps track of number of integers > > > > count=0 > > > > # Keep asking for an integer until we have the required number > > > > while count > new_int=raw_input("Please enter integer{0}:".format(count+1)) > > isint=False > > try: > > new_int=int(new_int) > > except: > > print("You must enter an integer") > > - > > > > > > On Tue, Nov 6, 2018 at 3:50 PM Joseph Gulizia > > wrote: > > > > > I'm using the bookazine "The Python Book" First Edition on pages > 13-14 it > > > gives the code (listed further below). > > > > > > It asks for user to state a given number of integers (for example > > > 4)...then user enters integers. It doesn't stop seeking input after > the > > > number requested thereby creating an infinite loop. > > > > > > - > > > CODE > > > - > > > > > > # Python Book Page_13.py > > > # Joe G. > > > > > > # several comment lines explain the code below it. > > > # Re-typing is good practice > > > > > > # We're going to write a program that will ask the user to input an > > > arbitrary > > > # number of intergers, store them in a collection, and then demonstrate > > > how the > > > # collection would be used in various control structures. > > > > > > # Used for the sys.exit function > > > import sys > > > # Requests number of intergers > > > target_int=raw_input("How many intergers?") > > > # By now, the variable target_int contains a string representtion of > > > # whatever the user typed. We need to try and convert that to an > interger > > > but > > > # be ready to # deal with the error if it's not. Otherwise the program > > > will > > > # crash > > > # Begin the error check > > > try: > > > target_int=int(target_int) > > > except ValueError: > > > sys.exit("You must enter an interger") > > > # creates a collection (list) called ints > > > ints=list() > > > # keeps track of number of intergers > > > count=0 > > > # Keep asking for an interger until we have the required number > > > while count > > new_int=raw_input("Please enter interger{0}:".format(count+1)) > > > isint=False > > > try: > > > new_int=int(new_int) > > > except: > > > print("You must enter an interger") > > > # Only carry on if we have an interger. If not, we'll loop again > > > # Notice below I use == which is different from =. The single equals > sign > > > is an > > > # assignment operator whereas the double equals sign is a comparison > > > operator. I would > > > # call it a married eguals signbut whenever single is mentioned I > have > > > to mention marriage. > > > > > > if isint==True: > > > # Add the interger to the collection > > > ints.append(new_int) > > > # Increment the count by 1 > > > count+=1 > > > # print statement ("using a for loop") > > > print("Using a for loop") > > > for value in ints: > > > print(str(value)) > > > # Or with a while loop: > > > print("Using a while loop") > > > # We already have the total above, but knowing the len function is very > > > # useful. > > > total = len(ints) > > > count = 0 > > > while count < total: > > >print(str(ints[count])) > > >count +=1 > > > > > > count = 0 > > > while count < total: > > > print(str(ints[count])) > > > count += 1 > > > > > > --- > > > END OF CODE > > > --- > > > Sample output: > > > > > > How many integers?3 > > > Please enter integer1:1 > > > Please enter integer1:2 > > > Please enter integer1:3 > > > Please enter integer1:a > > > You must enter an integer > > > Please enter integer1:4 > > > Please enter integer1:5 > > > Please enter integer1:6 > > > Please enter integer1:b > > > You must enter an integer > > > Please enter integer1: > > > (Keeps Looping) > > > > > > Thanks in advance > > > Joe > > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > https://mail.python.org/mailman/listinfo/tutor > > still not indented.. sorry.. figure that out > > -- > Joel Goldstick > http://joelgoldstick.com/blog > http://cc-baseballstats.info/stats/birthdays > ___
Re: [Tutor] Request for help with code
On 06Nov2018 15:50, Joseph Gulizia I'm using the bookazine "The Python Book" First Edition on pages 13-14 it gives the code (listed further below). It asks for user to state a given number of integers (for example 4)...then user enters integers. It doesn't stop seeking input after the number requested thereby creating an infinite loop. It is vital to preserve the indenting when pasting in code. Indent level is critical to Python's control flow. I'm going to look anyway, but without the indenting I may misinterpret the logic. [...snip...] # creates a collection (list) called ints ints=list() # keeps track of number of intergers count=0 # Keep asking for an interger until we have the required number while countHere is where I imagine the problem may lie, but it depends critically on the indenting. Your while loop should look something like this: while count < target_int: ... read the int ... if isint == True: ints.append(new_int) count += 1 However, consider this: while count < target_int: ... read the int ... if isint == True: ints.append(new_int) count += 1 All I have changed is the indent. This means that the increment of count is _outside_ the while loop body. Which means that it never happens inside the loop, and therefore count never increases, and therefore the end of loop condition is never reached. Infinite loop. The other likelihood is that isint somehow does not become true. If that is the case, the count also never increments. I suggest that you put several print() statements into the loop at strategic points (note the indenting - the same as the block they're embedded in): while count < target_int: print("loop: count =", count, "target_int =", target_int) ... read the int ... if isint == True: print("isint is true!") ints.append(new_int) count += 1 print("count =>", count) You should see that the expected code is actually reached and run, and if it isn't, the corresponding print()s do not happen. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On 11/6/18 4:36 PM, Joseph Gulizia wrote: > Funny using a text editorand showed indented in my browser. Won't > bother the list again. We don't want you to "not bother" us, just hoping to get things in a state where we can actually help... here's what we end up seeing: https://www.mail-archive.com/tutor@python.org/msg79222.html https://www.mail-archive.com/tutor@python.org/msg79225.html since unlike most other languages, indentation is a crucial part of the syntax, we tend to grumble. there must be some solution... guys, do you know of any alternate way to send a message to the list if a mail client isn't cooperating? or do we have instructions for beating gmail into submission? Obviously gmail is a key part of the modern infrastructure despite its (ahem) misfeatures. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
* Mats Wichmann [2018-11-06 16:54]: > > there must be some solution... guys, do you know of any alternate way to > send a message to the list if a mail client isn't cooperating? or do we > have instructions for beating gmail into submission? Obviously gmail is > a key part of the modern infrastructure despite its (ahem) misfeatures. Looking at the mail headers, I'm seeing Content-Type: text/plain; charset="us-ascii" But that is probably just what the final format that gets sent to the list ends up with. We might have some suggestions if we know for sure what email client is being used. A gmail.com address is not a guarantee that gmail within a browser is what's being used (I use mutt to send mail through my gmail.com account all the time). What's the MUA (mail client)? If it's in a browser, what browser is being used? Off the top, I would suggest looking for a "plain text" selection on a dropdown. -- David Rock da...@graniteweb.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex for Filesystem path
On 06/11/2018 19:47, Cameron Simpson wrote: > It is better to just construct the required path. Chdir there requires a > chdir back, and chdir affects all the relative paths your programme may > be using. > > I'd use os.path.dirname to get '/a/b/c/d/test' and then just append to > it with os.path.join to contruct each directory path. That was my original thought but the OP had his long path one below test so would need to strip one level off the dirname result. That's why I opted for chdir as the simplest solution(albeit not very efficient) > Do not use ctime, it is _not_ "creation" time. It is "last change to > inode" time. It _starts_ as creation time, but a chmod or even a > link/unlink can change it: anything that changes the metadata. Good catch, I should have known that. My bad. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On 06Nov2018 15:50, Joseph Gulizia ", count) You should see that the expected code is actually reached and run, and if it isn't, the corresponding print()s do not happen. Cheers, Cameron Simpson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] SyntaxError: can't assign to literal while using ""blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)" using subprocess module in Python
On 06/11/2018 18:07, srinivasan wrote: > bash command in python using subprocess module, I ma seeing the below > * cmd = "blkid -o export %s | grep 'TYPE' | cut -d"=" -f3" % (fs)* In general you should try to do as little as possible using bash and subprocess. Especially try to avoid long pipelines since you are starting a new OS process for every element in the pipeline. That means, in your case, you are running 4 processes to get your result - Python, blkid, grep and cut Python is designed to do much of what the shell command can do almost as easily and much more efficiently (no new processes being started). In this case just execute the blkid bit in bash because its too difficult to replicate simply in Python. Then use Python to search for the TYPE lines and slice them to size. That will, in turn, simplify your command string and remove the issue of multiple quotes. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex for Filesystem path
Hello, There are specific operating system, path related modules in Python for handling these scenarios. You could try looking at os.path module. On Tue, Nov 6, 2018 at 11:16 PM Asad wrote: > Hi all , > > Can you provide some advice and code for the following problem : > > I have a logfile to check for errors : > > /a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log > > f3 = open ( r"/a/b/c/d/test/test_2814__2018_10_05_12_12_45/logA.log", 'r' ) > st1 = f3.readlines () > > from the above log I extract the directory location to determine the > location of another log using the following regular expresssion: > Specifically, try exploring "dirname" function of os.path module. That might come in handy for your situation. -- Thanks -- Sarfraaz Ahmed ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Request for help with code
On Tue, Nov 06, 2018 at 06:32:25PM -0500, Joel Goldstick wrote: [snip nearly seven screens of quoted text] > still not indented.. sorry.. figure that out Hey Joel, is the Backspace key on your keyboard broken? :-) This sort of mass (and unnecessary) quoting is why Bottom-Posting gets a bad reputation. The reader shouldn't have to scroll through 6+ screenfuls of text to see your one, solitary comment. Please snip the quoted text to the minimum needed to establish context. If your mail client doesn't allow deleting the quoted text (and you can't get a better mail client!) it is better to Top-Post (heresy!), provided your signature shows up above the quoting so we know to stop reading. Thanks in advance, -- Steve ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor