585,759 active members*
3,910 visitors online*
Register for free
Login
Page 2 of 3 123
Results 21 to 40 of 57
  1. #21
    Join Date
    Sep 2009
    Posts
    96
    There are a number of methods you can use to handle(play),
    with files.
    I will start off with just a few.
    They are powerful because of their simplicity and are extremely
    useful.

    But we must remember an important thing here.
    When you do something, it's done 'finito'.
    You can't go back, it's irreversable.
    So you must 'think' first, before you command 'action' second.

    -------------------------------------------
    To write to a file, using 'w' for 'write';
    -------------------------------------------
    When you use 'w', the program will write whatever you want
    to the file you state by it's address in the (toolbox)
    If that file contains data you want to keep, you will lose it.
    The program will overwrite the entire file with your new text.
    If the original file had 10,000 lines of text and you write
    1 line of text to the file, all 10,000 lines will be errased
    and you will be left with a file containing your 1 single line.
    If the file in the (toolbox) doesn't actually exist, the program
    will automatically create a new file with that name and write you're
    text to it.

    fob = open ('c:/temp/trial.txt','w')
    newline = "I've just written a line\n"

    fob.writelines (newline)
    fob.close() # don't forget to close it properly using fob.close()
    print newline
    # print newline, just prints up your text at the Python IDLE as well

    ----------------------------------------------------
    To add a line of text to a file use 'a' for 'amend'.
    ----------------------------------------------------
    It will become the very next line at the end of the text file.

    fob = open ('c:/temp/trial.txt','a')
    newline = "I just added a line\n"

    fob.writelines (newline)
    fob.close()
    print newline

    If you go to you're file, trial.txt, you should find you're new line
    added to the end of the file.

    -----------------------------------------------
    To read a text file you can use 'r' for 'read'.
    -----------------------------------------------
    By simply using 'print fred',
    the entire file will be printed to the Python IDLE

    fob = open ('c:/temp/trial.txt','r')
    fred = fob.readlines()
    fob.close()
    print fred

    -----------------------------------------
    Here's another way to use 'r' for 'read'.
    -----------------------------------------
    Here I'm using 'with' 'open' 'as'

    Code:
    with open('c:/temp/trial.txt','r') as fob:
       harry = fob.readlines()
       fob.close()
       print harry
    The result is the same, but it's a cool way to get there
    I use this often.

  2. #22
    Join Date
    Sep 2009
    Posts
    96
    Here's the entire code group.
    Run this and check out your results.
    From 'readlines',
    you're lines are printed to the Python IDLE,
    all nicely packaged in a list [ ].
    This is going to be very useful to us.
    Remember our search 'extractions'?

    Code:
    import os
    import os.path
    
    fob = open ('c:/temp/trial.txt','w')
    newline = "I've just written a line\n"
    
    fob.writelines (newline) 
    fob.close()    # don't forget to close it properly using fob.close()
    print newline 
    # print newline, just prints up your text at the Python IDLE as well
    
    
    fob = open ('c:/temp/trial.txt','a')
    newline = "I just added a line\n"
    
    fob.writelines (newline)
    fob.close()
    print newline
    
    fob = open ('c:/temp/trial.txt','r')
    fred = fob.readlines()
    fob.close()
    print fred
    
    with open('c:/temp/trial.txt','r') as fob:
       harry = fob.readlines()
       fob.close()
       print harry

  3. #23
    Join Date
    Sep 2009
    Posts
    96
    ------------------------------------------
    Here's another way to use 'r' for 'read'.
    ------------------------------------------
    This time I use f.read()
    The file will be printed to the screen in a more human way,
    so that you can read it normally.

    This can be used to quickly 'view a configuration file'.

    Code:
    with open('c:/temp/trial.txt','r') as f:
        read_data = f.read()
    f.close()
    a = read_data
    print a

  4. #24
    Join Date
    Sep 2009
    Posts
    96
    ----------------------------------------------------
    Now we might want to check if a file actually exists
    ----------------------------------------------------
    Here I use 'try' and 'exept IOError'

    We use 'try' to just look for a file.
    If the file does not exist, the program would hang up because it
    got back a 'false' answer.
    So we tell the program that it's ok if the file doesn't exist.
    So we give it an escape route, 'exept IOError'

    Then we tell it 'print', give us back 1 of 2 answers.
    Instead of an answer, we could tell the program to do something
    completely different based on the result of 'try'
    We could tell it to do as many things as we like.
    Try this out by running it and then change the file name 'trial'
    in the (toolbox) to a file name you Know already doesn't exist.

    This is going to be important to the program later.

    Code:
    import os.path
    
    try:
       checkifilethere = open('c:/temp/trial.txt','r')
    except IOError:
       print "Program file searched for, does not exist"
    print "this file exists"

  5. #25
    Join Date
    Sep 2009
    Posts
    96
    When we use 'exept IOError', we are 'handling exeptions'.
    In our program we may have many configuration files, so when we
    create new files, it's a good idea to give the program the ability
    to search a directory and warn us if we attempt to overwrite a file
    by name, that aleady exists with that name.

    What if we want to purposefully overwrite a file, but we have another
    program looking at the same file at the same time.
    For simplicity, we may want to send our program output to the same file
    many times.
    Let's say that this file is one that we get 'Mach' to import and run with.
    When 'Mach" imports a G-code file, it does so in a similar way that we
    use the 'fileIN' method to open a file.
    The file is opened by 'Mach' and will keep it open until we tell it to
    'close G-code file'.
    So while the file is being used by another program or 'process', the file
    cannot be written to.

  6. #26
    Join Date
    Sep 2009
    Posts
    96
    If you have a version of the 'Mach' indexer installed on your computer,
    you'll be able to test that this sample python code actually works.


    Code:
    testhefile =''
    
    try:
       fob = open('c:/temp/trial2.tap','w')
       try:
          testfileopen = fob.readline
          testhefile =(testfileopen)
       finally:
          fob.close()
    
    except IOError:
       print """ 
    
    The file, cannot be written to at the moment.
    
    Another program may be using it.
    Check that you have closed the '*.tap' file, in 'Mach'
    
    Then, try again.
             """ 
       pass
    if testhefile !='':
       print 'the file you want, can be opened for writing to.'

    Open Windows notepad, and write a couple of lines of G-code in this file.
    Make sure that the code is correct, so as not to upset 'Mach'.
    This G-code below should be ok for your .tap file;
    Code:
    G54
    G21
    G90
    G17
    G94
    G48
    G0 Z10.000
    G0 X0.00 Y0.00
    G0 X20.00 Y20.00
    G0 X0.00 Y0.00
    M49
    M30
    ()
    Now save the file in your temp folder
    Name it trial2
    Now go to c:/temp and find your file using windows explorer.
    Right mouse click on the file and change it's file extension to .tap
    Now open 'Mach'
    Load your G-code file.... trial2.tap into 'Mach' and leave it open.

    Now run your 'test if the file is open already' Python code and
    see what you get.

  7. #27
    Join Date
    Sep 2009
    Posts
    96
    Just a little note on Python code writing.
    This may seem 'child like', but programs and computers are 'child like' in many ways.

    In a small way, we could think about Python as being like the little guy in a 2D
    arcade game.

    'functions', 'methods', 'if', 'else', 'try', 'for' code routines,
    could be seen as 'rooms' that the little guy is told to look in or enter.
    'While' (and this is another one) he's in a 'room', he has to find clues and get answers
    before he can leave, then he can go on to the next room in the game.

    We really need to give the little guy, 'Python' a way to escape from each room.
    Like most games, if he can't find a way out, it's game over.

    Sometimes we can let the guy open the door and just look in without entering at all.
    We can do this with 'if'
    Open the door and peek inside, 'if' it's ok, then go in.
    'if' he doesn't like what he sees he can close the door and go somewhere else.
    'if' he does like what he sees, he can go in.
    Once in, the door is slammed shut and locked.
    We can give him another 'if' or an 'elif' or an 'else' that he can use to find the key
    IE: an answer to unlock the door to let him leave, to continue on with the game.

  8. #28
    Join Date
    Sep 2009
    Posts
    96
    Let's look at how to create a DIR ... file folder for Windows

    Below is a function 'method' to create new file folders
    This is of course not indented, it's just to show the codelines.

    def createPath(path):
    if not os.path.isdir(path):
    os.mkdir(path)

    Now you can call on the function 'method', to create 1, or many folders.
    Just include the path, then a name for the folder or folders you want
    to create in the (toolbox)
    In this instance, the \\ backslashes shown like this are important.
    The second \ is the backslash and the first \ is an escape for the 2nd backslash
    Yeah weird.

    createPath("C:\\harry") this creates a harry folder on c drive

    createPath("C:\\harry\\harry2") this creates a harry2 folder inside the harry folder

    Once again I have to warn you,
    Just like writing to a file, if you already have a folder called 'harry' and there are
    lots of files contained in 'harry' and these files are important to you, they will be erased!!
    Python creates you a new 'Empty' and ready to use 'harry' folder.

    We will include with our file and folder creation functions,
    checks and balances to prevent unwanted deletion of our precious files.
    These aren't hard to include.
    We can precede a folder creation, with a 'does file or folder already exist?' similar to what we have covered previously.

    Here is the function 'method' with 2 calls to the function below

    Code:
    import os   # get the module in first
    
    def createPath(path):
        if not os.path.isdir(path):
            os.mkdir(path)
    
    
    createPath("C:\\harry")
    createPath("C:\\harry\\harry2")
    Now go and look at c drive using windows explorer.
    You should see the folder 'harry' and if you open 'harry',
    you should find 'harry2'

  9. #29
    Join Date
    Sep 2009
    Posts
    96
    these are our topics covered so far;
    ------------------------------------------
    1: import the needed python process modules
    2: open a file to read
    3: search function(method)
    4: all search 'actual' functions
    5: all calls to the 'actual' functions
    6: creating a file object.
    7: read file, print to console
    8: write to file, print to console
    9: amend to file, print to console
    10: how to check if a file actually exists or not
    11: handle some file opening to read or write exceptions
    12: how to create DIRs (file folders)

    Below are topics that still have to be covered, that will give everyone
    the tools needed to construct the framework of our program.
    ------------------------------------------------------------------------
    how to create 'Program Main'

    how to create a menu
    how to loop over a menu
    how to link the menu items to functions
    how to get out of a menu

    how to construct raw input properly to gather information
    how to save the information and include a name for a config file
    how to create auto file extension completion

    how to check a file for values on file lines of a config file
    how to enumerate and print to screen, files within a folder
    how to get all values from the file, and store it to use
    how to 'select' a file to process
    how to link the 'selected' file to a process

    how to create some loops 'for' and 'while'
    how to construct and include actual G-code line arguments
    how to break loops with self imposed events
    how to break loops using G-code read events
    -------------------------------------------------------------------------
    When we are done with these, we can begin the task of examining the important
    indexer's requirements and begin to write code to satisfy each requirement.
    And we should all be at a similar level with using Python.

  10. #30
    Join Date
    Sep 2009
    Posts
    96
    Lets take a look at the 'Program Main' function.

    When we run a complete program, we want it to begin at a place
    where we can tell it to perform anything we have given it the ability
    to do so.
    If a program can do many different things, then we need to be able to
    choose exactly which one of these things we want it to do for us.
    We don't want the program to just blindly start processing something.

    To acheive this, we will need a program menu.
    But this menu has be placed where we have control over it.
    We place it within a 'main' function.
    This function could be named anything at all, like 'fred' or 'harry',
    but 'main' is an obvious choice for a name.

    'Main' is very simple, it just has a way in and a way out.
    Python automatically gets you into 'main' with the call;
    main()

    Once you're inside, Python will wait, because of a call for you're input;
    leave = raw_input("\n\nPress Enter to quit and close 'main' : ")
    if leave == "\n":
    pass

    'leave' gets you out completely, then Python closes the program automatically,
    because there is no more code to process.

    Below is an example of 'main'

    Code:
    #========================================================
    # many many functions will be placed above 'Program Main'
    def main():
        print """
    
        This is the 'main' function where you bind everything together.
        We place 'main' at the end of our program.
        We place all of the program's blocks of function processes, above 'main'.
        All menu items and calls to these large process blocks, will be placed
        within this 'main' function.    
        When we run the complete program, we will tell it to start from here only.
        We will command our program to perform every action it is capable of,
        from here.
        """
        leave = raw_input("\n\nPress Enter to quit and close 'main' : ")
        if leave == "\n":
            pass
    main() # this is the automatic call to the program's 'main'
    #========================================================
    Copy program 'main'
    Name the program ... Program Main.py and save it to your C:temp folder.

    Now open windows explorer, go to your temp folder.
    Double click on your 'Program Main.py'
    You should see the program open in a console window.
    This is the real beginning.
    Although tiny, this is a fully functional program, ready and
    waiting to be told what we want it to do and how it should go
    about doing it.

  11. #31
    Join Date
    Sep 2009
    Posts
    96
    Lets look at a simple menu.

    I have placed the menu inside 'main'

    We run a menu within a 'while' loop.
    The 'while' loop will run forever until an 'event'
    causes it to stop.
    I was going to cover loops later, but we need to use one now.


    Here is 'main' with a 'menu'

    Code:
    #========================================================
    # 1st you'll need these;
    #========================================================
    import os
    import os.path
    #========================================================
    # then you'll need this;
    #========================================================
    def cls():
        os.system(['clear','cls'][os.name == 'nt'])
    
    # use  'cls()'  to call  'clear screen'  when you run a menu item.
    #========================================================
    
    def main():
        item = None
        while item != "0":
            cls()
            print """
    
       =============    THIS IS THE MAIN MENU    ================
    
                         Type an item number,
                      then press Enter to run it
    
    """
            print "   1.  ....IMPORT\n"
            print "   2.  ....PROCESS\n"
            print "   3.  ....VIEW\n"
            print "   4.  ....CHANGE\n"
            print "   5.  ....HELP\n"
            print "   0.  ....CLOSE"
            print """
        =========================================================
    """
    
            item = raw_input ("\n\nType an Item number: ")
            if item == "1":
               cls()
               print "\n\nFile import could run here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
    
            elif item == "2":
               cls()
               print "\n\nThe imported file could be processed here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
     
            elif item == "3":
               cls()
               print "\n\nThe program could show a control file, here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
    
            elif item == "4":
               cls()
               print "\n\nYou could change a control file's settings, here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
    
            elif item == "5":
               cls()
               print "\n\nYou could print up a help file, here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
    # here we call 'main'
    main()
    
    #========================================================

    In this instance, we impose on 'while', a 'condition'.
    This must remain 'true' at all times for it to continue.
    The condition is;
    While the user's key stroke - entry, is not equal to 0.

    The variable 'item', will always take on the value of the
    user's keyboard entry.
    from;
    item = raw_input ("\n\nType an Item number: ")
    The program will argue the user's entry.

    The user may give the variable 'item' , an entry like this;
    3\n
    The '\n' is the carriage return and the program will ignore this.
    It only processes the number.

    If the user types any item number other than 0, then
    the 'while' loop will continue, because the argument based on
    the conditional statement will come back as 'false'.

    The menu calls have there own 'if' statements, so the program will
    only do something if one of the item numbers is entered.

    If the user enters 'f' or 'h' or '205' nothing will happen, the
    program will not hang up on you.
    The loop will just wait until it's 'while' conditional statement
    becomes true.

    If a key stroke is 0(zero), it evaluates to 'true' and the loop breaks.
    From that point, Python will look for another command after the loop,
    but because there is none, the program will quit.

    Copy this, give it a name.py
    then run it from windows explorer by double clicking on the file.
    You should have a program with a fully functioning menu.
    Now you can copy the program file, give it another name, mess around
    with the code, like add more items to the list, change the item names.

  12. #32
    Join Date
    Sep 2009
    Posts
    96
    We know already that 'variables' store values and
    are also used to 'call' on functions.
    Functions can also 'call' other functions.

    This is a call to a function;
    fredOne()
    We just state the function name with () at the end.
    There's no need for ':' to be included as we aren't
    declaring anything. We are just making a 'call'.

    When any function is 'called', the program will run it.
    Let's have a menu item call on a function.

    Our menu is already within the function 'main', so this
    will prove the 'function call to function'.

    Here is a simple function followed by 'main' with a shortened 'menu'
    Look at how I altered item 2, to call the function above 'main'.
    Copy, name, save.py and run the program from windows explorer.
    Try menu item 2



    Code:
    # 1st you'll need these;
    import os
    import os.path
    
    # then you'll need this;
    #====================================================
    def cls():
        os.system(['clear','cls'][os.name == 'nt'])
    
    # use  'cls()'  to call  'clear screen'  when you run a menu item.
    #====================================================
    
    # here's a function
    def simpleCascade():
        linestooutput = 4
        stopcount = 0
        inputline = 1
        lineplus = ''
    
        # now process the main part of the input line and give the values to newparse 
        newparse = '' # this gets the values of the input line
    
        # now process lastparse angle with the angle of the newparse to find the incidence.
        lastparse = ''
    
        addtoparse = '' # this gets the angle of incidence added to the list
        parseout = ''
        # parseout should always be one step behind newparse
        # when parseout is sent, assign last parse with the value of newpass before looping again. 
        # lastparse should retain the value given until it's re-assigned again at the end of the next
        # loop. 
    
        while stopcount != linestooutput:
            if inputline <= linestooutput:
               newparse = 'inputline',inputline     
               # line parsing would happen here, find the angle
               lastparse = 'angle,',newparse
    
               addtoparse = 'incidence,', lastparse
               parseout = addtoparse
               stopcount = stopcount + 1
               lineplus = inputline + 1
               print newparse
               print lastparse
               # find the angle of incidence, would happen here
               inputline = lineplus # make the change to the input line
               print parseout
        print '\n\n\nThe program just ran a simple cascade process.'
        toleave = raw_input("\nPressing Enter, starts the return to the menu .. :")           
    
    # here's main
    def main():
        item = None
        while item != "0":
            cls()
            print """
    
       =============    THIS IS THE MAIN MENU    ================
    
                         Type an item number,
                      then press Enter to run it
    
    """
            print "   1.  ....IMPORT\n"
            print "   2.  ....PROCESS\n"
            print "   0.  ....CLOSE"
            print """
          =====================================================
    """
    
            item = raw_input ("\n\nType an Item number: ")
            if item == "1":
               cls()
               print "\n\nFile import could run here\n"
               goback = raw_input ('\n\nPress enter .... Return to Main Menu: ')
               if goback == "\n":
                  pass
    
            elif item == "2":
               cls()
               begin = raw_input ('\n\nPress enter to start the function: ')
               cls()
               simpleCascade()
               goback = raw_input ('\n\nPress enter again: ')
               if goback == "\n":
                  pass
    
    # here we call 'main'
    main()

  13. #33
    Join Date
    Sep 2009
    Posts
    96
    I need to briefly review a previous post where I referred to;
    'checkifilethere'
    Here is the code from that post.
    Code:
    import os.path
    try:
       checkifilethere = open('c:/temp/trial.txt','r')
    except IOError:
       print "Program file searched for, does not exist"
    print "this file exists"
    It's a check to see if a file actually exists in the file system.
    Although this works to a degree, the result is ambiguous (not definitive)
    What we really need is a 'True' and 'False' test.
    Now you can't really argue these 2 things directly.
    At least not in the way we may think of an argument.
    I'll try and explain this as best I can and hope this isn't too confusing.

    Here is another approach to checking the existence of a file or folder;
    Code:
    import os
    import os.path
    
    pathisthere = 0
    print "the value of the variable 'pathisthere' starts as ...", pathisthere,"\n"
    
    print "Now the program decides if our 'if' statement is correct;\n"
    
    if os.path.exists('c:/temp/trial.txt'):
       pathisthere = 1
    else:
       pathisthere = 0    
    
    if pathisthere == 1:
       print "The path searched for exists"
    elif pathisthere == 0:
       print "The path searched for does not exist"
    
    
    print "The value of the variable 'pathisthere' is now ...", pathisthere,"\n"
    
    checkifilepathere = raw_input("Where done here, press enter to close :")
    We started with the variable, 'pathisthere' and assigned it '=' with the value '0'.
    Then we gave an 'if' statement;
    if os.path.exists(): and placed our path inside the parentheses (toolbox)

    'if' is not actually a question asked of the program.
    It's not really commanding the program to return a 'True' or a 'False' answer.
    'True' and 'False' describe a 'state', as in, the 'state' of a 'path' is good or not.
    It's more like allowing the program to merely agree or disagree with us.

    The very real command is the 'indented' line directly below the 'if' statement.
    If the if's 'state' is True, then the program will carry out the related task;
    pathisthere = 1 (re-assign the variable with the number 1)
    Because of it's 'indentation', 'pathisthere = 1' is the actual related task.
    When this is done, it will ignore the else: statement that follows.

    If the if's 'state' is False, the program is not going to carry out the task,
    because it disagrees with our if statement.
    It will ignore, pathisthere = 1.
    It will instead, look elsewhere, for something else to do.

    else:
    By not carrying out pathisthere = 1,
    the program must now carry out whatever task is related by 'indent' to else;
    pathisthere = 0 (assign the variable with 0)
    And it won't matter if the value of 'pathisthere' is already '0'.

    We have given Python the opportunity to make a tangible change to a variable,
    based on it's own test of our 'if' statement.

    The program can now continue onward with whatever follows.
    It can be given some 'if' and 'elif' statements to give us back clearly defined
    answers in a more human way, because now we can 'directly argue' the value
    of the variable named pathisthere.

  14. #34
    Join Date
    Sep 2009
    Posts
    96
    Big apologies to anyone reading my posts.
    I have been busy these last weeks, so I've had no spare time.
    I have just concluded a new program for the translation of G-code to HPGL.
    This is of course for just one type of HPGL.
    There are many different HPGL flavors.
    The program will be tested on a 'targeted' 3 axis CNC router/engraver tomorrow.
    The indexer is used by the 'U.S.A .Multicam' model 'Matcam 3000'.
    There may be bugs, but you gotta start somewhere.
    They are of course minor to the main objective and will be quickly sorted.
    The 'Multicam' indexer is extremely effective and very well designed,
    so if my program is well thought out , all should go well.

  15. #35
    Join Date
    Jan 2006
    Posts
    357
    I am also watching your thread with great interest, I understand that everyone has other things that they have to do

  16. #36
    Join Date
    Sep 2009
    Posts
    96
    Back again,
    and thanks for the feedback Gary.
    The HPGL converter is successful and now in use. Only 1 small 'bug' needed fixing.
    It was a minor problem but it took some time to come up with a solution.
    I will at a later stage, go over some of the methods used in this program, as they
    do relate to the requirements of an indexer.
    I'll get together some notes and we'll continue with our adventure.

  17. #37
    Join Date
    Sep 2009
    Posts
    96
    How to construct raw input properly to gather information.
    ----------------------------------------------------------
    Getting information from a user and storing this in a file
    can be important when using Python.
    You can script your variables in Python to retain permanent
    values.
    When these values are assigned in your script, they will remain
    constant or (current), until they are temporarily re-assigned
    during a program run.
    Then when you run the program again, they will appear as they were.

    But if you want you're program to be flexible, configuration files
    are not only very useful, but needed.
    There are different ways to achieve this.
    One way is to use a 'Pickle' process.
    I'm not going to use this yet, because at this time, ,Pickling'
    isn't needed.
    But I will describe it briefly.

    Normally when you write to a file, the data is output as strings of
    text only.
    You may have numbers included in the text, but they are still
    just text.
    If you have output to a file, text numbers, they are not processable
    numbers meaning, you can't just import them as text and add, subtract
    or multiply them.
    You have to convert them back to real numbers within the program before
    you can do anything useful with them and often this doesn't matter.
    Now this procedure wastes a huge amount of time.
    It may take a nano second to achieve this.
    "fast enough" you may say,.... "slow" I say, "painfully slow".
    If the program has to process 50,000 lines of code, you might want to
    go and brew yourself a coffee while you wait for this to get done.

    'Pickling' on the other hand, allows you to write 'numerical data'
    directly to file, as it is.
    Then bring it back again at any time, ready to use, as real numbers
    exactly how the numbers existed before they were 'Pickled'.
    Pickling, encodes data then decodes data, very, very quickly.

    Python has 2 flavors for Pickling, cPickle and Pickle.
    Later on, we are going the use cPickle.
    'cPickle, as you may guess, is written in pure 'c'.
    All processes written in 'c', are up to 1,000 times faster than
    anything written in pure Python.
    Python as a whole is created using both 'c' and 'Unix'.
    Python, being an 'interpretive' language is structured to make
    life easy for 'us', the user.
    Python mostly does all the mundane and tedious scripting for us.
    Because of this, there is a trade off with processing speed.
    But be assured, when 'push comes to shove', the 'c' and 'unix'
    components of Python, will kick some serious butt.

    So, without going any further on 'Pickling' at the moment,
    We have to write numbers to file as text, then when the
    text numbers are brought back, the program is going to have to
    convert the text back to numbers again, in the snail way.
    At this point in the program ,we really won't need high speed
    conversion.

    We can get raw_input from the user and send this to a file.
    Raw input can run in a sequence, so that we get more than just a
    few items of information.
    Some tricks to getting the right information are;
    Word the questions carefully.
    Argue the user's input logically.
    Write the info to file precisely.

    To make writing to file precise, it's a good idea to create
    a 'road map' of a file.
    personaly, I write these using notepad.
    When a program starts to get large in size, I need lots of notes,
    To remind me where things are.

    Lines of text in a file are like the elements in a list.
    Files are of course, just a big list.
    Line 1 in a file is situated at position 0 and line 2 would be at
    position 1 etc., etc, the same as a list.

    When we want to write a line of text to a file and place it in an
    exact position in a file, we can just assign it to the numerical
    position that corresponds to the line number we want to
    write it to.

    If a file exists;
    We open the file as a list (object).
    We can simply alter the list elements (lines), by their numerical
    address within the list.
    Then, when done, just write the [list] to the same file,
    which as we know, overwrites the entire file.

    If a file doesn't already exist;
    We just create a list, then the list is written and saved as a file.
    Each element in the list will become a line of that new file.

    I will also advance on the naming of files when they are created.
    At this time if you try the name a file and write to it, using
    multiple words with spacegaps (whitespace), this will fail.

    I will explain in full, the entire work around for creating file names
    in a windows environment with multiple words including spacegaps.
    We will need this capability.

    HELP needed !!
    I have a request to anyone following my posts.
    before I can continue properly:
    We are going to have to give this program a real name.
    When we write to file, open file, check file or anything else,
    it will be easier for all, most of all me.

    I went and got all 'creative' and came up with the name 'PyNC'.
    If anyone has a better name, let me know and we'll have a new name,
    but we must have a program 'name', for code addressing.

    First one to post, gets to name the program, of course really 'rude'
    words are out,
    but I'm not totally without a sense of humor.
    That said, all references will be then be attributed to the program's 'name'.

    If no one posts a new 'name', yawl get stuck with wait for it, ..... 'PyNC'.
    Sounds like a pizza, I don't do sport .. and .. I don't do pizza.

    So help me out here someone .. pplease

  18. #38
    Join Date
    Sep 2009
    Posts
    96
    It seems that PyNC wins.
    Being busy these last couple of weeks, I've lost some ground
    with this project, so I decided it was better to script a large peice of
    the program and post it.
    It is fully functional, minus the G-code line searches and line arguments.
    I have already covered the g-code line searches but not the arguments
    for output to file.
    That's going to be full on and a real brain twister.
    So for now just have some fun with the basic PyNC program.

    Make a new window in Python and paste the entire code into it.
    Save the file as PyNC.py
    Then save this to your temp folder or your desktop.
    Close python.
    Now when you double click on the PyNC file, it will run.
    It will at first create all of it's own folders and program files on
    your c: drive.
    You will find them in the newly created folder... PyNC
    Every time you run it after that, it will just run through a self check.
    It will not yet be able to parse G-code.

    I still have to explain some of the very important features in the program.
    It's just easier to describe raw_input and configuration file use, when you
    can see it in action at the same time as I do so.
    You will find 'long file name' saving and other features already to use.

    When I've explained most all of the features, we'll get into G-code crunching.


    Here's the program:
    Code:
    # The program name is PyNC
    import os
    import os.path
    import time
    import math
    import re
    #======================================================
    # Below is a function to make new file folders
    #======================================================
    def createPath(path):
        if not os.path.isdir(path):
            os.mkdir(path)
    #======================================================
    def cls():
        os.system(['clear','cls'][os.name == 'nt'])
        # use this below, to clear the screen
    # cls()
    #======================================================
    # Search function for user input is directly below
    #======================================================
    def Userstringsearch(pat, line):
         match = re.search (pat, line)
         if match: return match.group()
         else: return ""
    #==============================================================
    # Search function to Parse lines is directly below
    #==============================================================
    def Find(pat, line):
         match = re.search (pat, line)
         if match: return match.group()
         else: return ""
    #==============================================================
    # variables below are needed to create a blank ncv file
    #======================================================
    
    n0 = '  ncv file\n'
    n1 = '  Mill depth    Z      \n'
    n2 = '  plunge speed  Z      \n'
    n3 = '  mill speed   XY      \n'
    n4 = '  clear         Z      \n'
    n5 = '  lift          Z      \n'
    n6 = '  rapid down    Z      \n'
    
    ncvlines = n0+n1+n2+n3+n4+n5+n6
    
    #==========================================================
    # These are the lines for the very first 'parsefile'  file'
    # The program will only parse from this file
    #==========================================================
    ps0 = """ \n\n\n\nThis is the temporary parse file.
    \nWhen the user selects and loads a G-code file from the 'import file' folder,
    The contents of that G-code file are copied and then written to here.
    \nThe program will only parse code from this file.
    \nWhen the program has parsed it's first file, this message will be erased.
    """
    #==========================================================
    
    PyNCisthere = ''
    
    importisthere = ''
    
    outputisthere = ''
    
    programisthere = ''
    
    myncvisthere = ''
    
    blankncvisthere = ''
    
    controlncvisthere = ''
    
    parsefileisthere = ''
    
    updatencvisthere = ''
    
    # run a self check before program start
    
    print 'DIR check\n'
    time.sleep(0.3)
    #=========================================
    # find PyNC program folder
    if os.path.exists('c:/PyNC'):
        PyNCisthere = 1
        print "PyNC program folder found"
    else:
        PyNCisthere = 0    
        print "PyNC program folder not found"
    if PyNCisthere == 0: 
        createPath("C:\\PyNC")
        PyNCisthere = 1
        print 'PyNC folder, created'
    time.sleep(0.1)
    #=========================================
    # find import files folder
    if os.path.exists('c:/PyNC/import files'):
        importisthere = 1
        print "\nimport files folder found"
    else:
        importisthere = 0 
        print "\nimport files folder not found"
    if importisthere == 0:
        createPath("C:\\PyNC\\import files")
        importisthere = 1
        print 'import folder, created'
    
    #=========================================
    # find output files folder
    if os.path.exists('c:/PyNC/output files'):
        outputisthere = 1
        print "\noutput files folder found"
    else:
        outputisthere = 0    
        print "\noutput files folder not found"
    if outputisthere == 0:
        createPath("C:\\PyNC\\output files")
        outputisthere = 1
        print 'output folder, created' 
    time.sleep(0.1)
    #=========================================
    # find program files folder
    if os.path.exists('c:/PyNC/program files'):
        programisthere = 1
        print "\nprogram files folder found"
    else:
        programisthere = 0    
        print "\nprogram files folder not found"
    if programisthere == 0:
        createPath("C:\\PyNC\\program files")
        programisthere = 1
        print 'program folder, created'
    time.sleep(0.1)
    #=========================================
    # find my ncv files folder
    if os.path.exists('c:/PyNC/my ncv files'):
        myncvisthere = 1
        print "\nmy ncv files folder found"
    else:
        myncvisthere = 0    
        print "\nmy ncv files folder not found"
    if myncvisthere == 0:
        createPath("C:\\PyNC\\my ncv files")
        myncvisthere = 1
        print 'my ncv files folder, created'
    
    #==========================================================
    # now check on the important files
    print '\nfile check\n'
    time.sleep(0.3)
    #=========================================
    if os.path.exists('c:/PyNC/program files/blankncv.prg'):
        blankncvisthere = 1
        print "blankncv found"
    else:
        blankncvisthere = 0    
        print "blankncv not found"
    if blankncvisthere == 0:
        fob = open ('c:/PyNC/program files/blankncv.prg','w')
        fob.writelines (ncvlines)
        fob.close()
        blankncvisthere = 1
        print 'blankncv file, created'
    time.sleep(0.1)
    #=========================================
    if os.path.exists('c:/PyNC/program files/controlncv.prg'):
        controlncvisthere = 1
        print "\ncontrolncv found"
    else:
        controlncvisthere = 0    
        print "\ncontrolncv not found"
    if controlncvisthere == 0:
        fob = open ('c:/PyNC/program files/controlncv.prg','w')
        fob.writelines (ncvlines)
        fob.close()
        controlncvisthere = 1
        print 'controlncv.prg file, created'
    time.sleep(0.1)
    #=========================================
    if os.path.exists('c:/PyNC/program files/updatencv.prg'):
        updatencvisthere = 1
        print "\nupdatencv found"
    else:
        updatencvisthere = 0    
        print "\nupdatencv not found"
    if updatencvisthere == 0:
        fob = open ('c:/PyNC/program files/updatencv.prg','w')
        fob.writelines (ncvlines)
        fob.close()
        updatencvisthere = 1
        print 'updatencv.prg file, created'
    time.sleep(0.1)
    #========================================================
    if os.path.exists('c:/PyNC/program files/parsefile.prg'):
       parsefileisthere = 1
       print "\nparsefile found"
    else:
       parsefileisthere = 0    
       print "\nparsefile not found"
    if parsefileisthere == 0:
       fob = open ('c:/PyNC/program files/parsefile.prg','w')
       fob.writelines (ps0)
       fob.close()
       parsefileisthere = 1
       print 'parsefile.prg file, created'
    time.sleep(0.1)
    #=========================================
    
    #============================================================================
    # this is the user input instructions
    def showchngeInstrctns():
        print """\n
    =======================================================
    =============    CHANGE CONFIGURATION    ==============
              """
    
        print """
    
        Veiw each configuration, one at a time.\n
        You can type any new setting then press Enter.
        or,    
        you can simply press Enter to 'skip' any item you don't
        want to change.
    
        When done, you can load the altered settings to the program.
        You can create and Name a new .ncv file.
        You can overwrite an existing file if you wish to.
    
        """
    #===========================================================================
    #===========================================================================
    def getzDepth():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolncv = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolncv)
        print """=============================================================
    =======================     Z DEPTH      ====================\n"""
        print "How deep do you want the Z axis to mill down to ?\n"
        print "\nThe current Z depth is... ", updatelist1[1]
        print """\nIf you just press Enter to skip,
    the current Z depth will remain.
    
        """
        print "Be certain to use a minus for anything below 0(the surface)\n" 
        userzdepth = raw_input("enter a depth, for Z to mill into the surface :")
        nn1 = '  Mill depth    Z      '
        newline = "\n"
        if userzdepth != "\n":
           consolein1 = Userstringsearch( r' *-*\.*\d\d*\.*\d* *', userzdepth )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zdepth = (string1strip)
                 updatelist[1] = nn1 + zdepth + newline
                 print updatelist[1]
                 return updatelist[1]
        else:
           pass
    
    #============================================================================
    #=============================================================================
    def getzplungeSpeed():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolgcf = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolgcf)
        print """=============================================================
    ====================    Z PLUNGE SPEED      =================\n"""
        print "What speed should Z enter the material ?"
        print "\nThe current Z plunge speed is... ", updatelist1[2]
        print """\nIf you just press Enter to skip,
    the current Z plunge speed will remain.
    
        """
        userzplunge = raw_input("enter a speed that Z will enter the material :")
        nn2 = '  plunge speed  Z      '
        newline = "\n"
        if userzplunge != "\n":
           consolein1 = Userstringsearch( r' *\.*\d\d*\.*\d* *', userzplunge )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zplunge = (string1strip)
                 updatelist[2] = nn2 + zplunge + newline
                 print updatelist[2]
                 return updatelist[2]
        else:
           pass
    #=============================================================================
    #=============================================================================
    def getxymillSpeed():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolgcf = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolgcf)
        print """=============================================================
    ====================     MILLING SPEED      =================\n"""
        print "What speed, do want XY to mill the material ?" 
        print "\nThe current milling speed is... ", updatelist1[3]
        print """\nIf you just press Enter to skip,
    the current milling speed will remain.
    
        """
     
        userxymill = raw_input("enter a speed for XY to mill the material :")
        nn3 = '  mill speed   XY      '
        newline = "\n"
        if userxymill != "\n":
           consolein1 = Userstringsearch( r' *\.*\d\d*\.*\d* *', userxymill )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 xymill = (string1strip)
                 updatelist[3] = nn3 + xymill + newline
                 print updatelist[3]
                 return updatelist[3]
        else:
           pass
    #=============================================================================
    #=============================================================================
    def getzClear():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolgcf = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolgcf)
        print """=============================================================
    =================     Z CLEARANCE HEIGHT      ===============\n"""
        print "You can clear clamps and fixtures when starting or going home."
        print "\nHow high do you want Z to lift clear ?"
        print "\nThe current Z clearance height is... ", updatelist1[4]
        print """\nIf you just press Enter to skip,
    the current Z clearance height will remain.
    
        """
        userzclear = raw_input("enter a coordinate for Z to clear any fixtures :")
        nn4 = '  clear         Z      '
        newline = "\n"
        if userzclear != "\n":
           consolein1 = Userstringsearch( r' *\.*\d\d*\.*\d* *', userzclear )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zclearance = (string1strip)
                 updatelist[4] = nn4 + zclearance + newline
                 print updatelist[4]
                 return updatelist[4]
        else:
           pass
    #=============================================================================
    #=============================================================================
    def getnormalzLift():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolgcf = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolgcf)
        print """=============================================================
    =================       NORMAL Z HEIGHT       ===============\n"""
    
        print "How high do you want Z to lift normally during a job run ?"
        print "\nThe current Z lift height is... ", updatelist1[5]
        print """\nIf you just press Enter to skip,
    the current normal Z lift height will remain.
    
        """
        userzlift = raw_input("enter a coordinate for Z to lift normally :")
        nn5 = '  lift          Z      '
        newline = "\n"
        if userzlift != "\n":
           consolein1 = Userstringsearch( r' *\.*\d\d*\.*\d* *', userzlift )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zliftnorm = (string1strip)
                 updatelist[5] = nn5 + zliftnorm + newline
                 print updatelist[5]
                 return updatelist[5]
        else:
           pass
    #=============================================================================
    #=============================================================================
    def getminzrapiDown():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolgcf = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolgcf)
        print """=============================================================
    ==================        Z RAPID DOWN       ================\n"""
    
        print "To save time, the Z axis can rapid move to a minimum height,"
        print "above the material surface."
        print "\nThe current Z rapid down height is... ", updatelist1[6]
        print """\nIf you just press Enter to skip,
    the current mimimum Z rapid down, will remain.
    
        """
        userzminrapid = raw_input("enter a height for Z to rapid down to :")
        nn6 = '  rapid down    Z      '
        newline = "\n"
        if userzminrapid != "\n":
           consolein1 = Userstringsearch( r' *\.*\d\d*\.*\d* *', userzminrapid )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zminrapid = (string1strip)
                 updatelist[6] = nn6 + zminrapid + newline
                 print updatelist[6]
                 return updatelist[6]
        else:
           pass
    #=============================================================================
    #=============================================================================
    # this is the  'question the user'  function
    # call userinPut() from one of the menu items at main().
    def userinPut():
        Openupdatencv()
        cls()
        showchngeInstrctns()
        tocontinue = raw_input("Press enter to continue... :")
    
        # Questions start from here
    
        cls()
        getzDepth()
        time.sleep(1)
    
        cls()
        getzplungeSpeed()
        time.sleep(1)
    
        cls()
        getxymillSpeed()
        time.sleep(1)
    
        cls()
        getzClear()
        time.sleep(1)
    
        cls()
        getnormalzLift()
        time.sleep(1)
    
        cls()
        getminzrapiDown()
        time.sleep(1)
    
        cls()
        print """
    
    ==================================================================
    =====================  ! !  S  T  O  P  ! !  =====================
    =====================         you can        =====================
    =====================         L O A D        =====================
    =====================     S E T T I N G S    =====================
    =====================          and           =====================
    =====================      create a new      =====================
    =====================        ncv file        =====================
    =====================      if you wish       =====================
    ==================================================================
        """
        print """
    
    If you have changed any settings, 
    You will be able to 'Load' these settings,
    The program would then use these to process the next G-code file.
    
    If you don't 'Load' settings,
    the program will continue to use it's last loaded settings.
    
    You will also be asked, if you want to 'Name' a new ncv file.
    You can overwite an existing file.
    These 2 actions won't 'load' any new settings. 
    
    You can just skip each one and don't do anything.
    
        """
        loadsettings = raw_input("""\n\nTo Load settings, Enter Y for yes,
        or just press Enter to skip loading ... :""")
        if loadsettings == "Y" or loadsettings == "y":
           with open('c:/PyNC/program files/updatencv.prg','w') as fob:
                fob.writelines (updatelist)
                fob.close()
           with open('c:/PyNC/program files/controlncv.prg','w') as fob:
                fob.writelines (updatelist)
                fob.close()
           print "\n\nDone"
        time.sleep(1)
        cls()
        namemyNcv()
    #=============================================================================
    # this is for naming a ncv file 
    def namemyNcv():
       successful = 0
       while successful == 0:
          cls()
          answer = raw_input("""   
    
     Go ahead and Type a Name for your ncv file then press Enter...
    
     OR you can,
    
     just press Enter only, to skip this.... :""")
    
          answerstring = str(answer) # make sure the answer is now a string
          answerstrip = (answerstring).strip()# strip any white space here
          newfile = (answerstrip) # this is the answer as a string
          extension = '.ncv'
          thename = 'No name.ncv'
          answername =  newfile + extension
          answername1 = str(answername)
          long_file_name = answername1
          filetest = os.path.exists('c:/PyNC/my ncv files/'+ answername1)
          if filetest == True:
             if answername1=='.ncv':
                file = open('c:/PyNC/my ncv files/'+ thename ,'w')
                file.writelines(updatelist)
                file.close()
                answername1 = thename
                long_file_name = answername1
                successful = 1
                cls()
                print "\n\n\nJust in case, PyNC has auto-saved the file as... "+  long_file_name
                getout = raw_input("\n        Press Enter to leave Naming... :")
                break 
          if filetest == False:
             if answername1=='.ncv':
                file = open('c:/PyNC/my ncv files/'+ thename ,'w')
                file.writelines(updatelist)
                file.close()
                answername1 = thename
                long_file_name = answername1
                successful = 1
                cls()
                print "\n\n\nJust in case, PyNC has auto-saved the file as... "+  long_file_name
                getout = raw_input("\n        Press Enter to leave Naming... :")
                break 
          if filetest == False:
             if answer!= '\n':
                file = open('c:/PyNC/my ncv files/'+ long_file_name ,'w')
                file.writelines(updatelist)
                file.close()
                cls()
                print "\n\n\nYou're new file named... "+long_file_name +" has been saved"
                successful = 1
                getout = raw_input("\n        Press Enter to leave Naming... :")
                break 
    #     #
          if filetest == True:
             if answer!= '\n':
                cls()
                print """
    
    There's already a file called... """ +long_file_name + """
    
    You can over-write this file if you want to.
    
    Type  Y  for yes  ....  or  N  for no.
    
                 """
                yesno = raw_input("\ntype Y or N .. then Enter, here... :")
                if yesno == "Y" or yesno == "y":
                   file = open('c:/PyNC/my ncv files/'+ long_file_name ,'w')
                   file.writelines(updatelist)
                   file.close()
                   cls()
                   print """
    
    The existing file called.. """+ long_file_name + """ 
    has been over-written"""
    
                   getout = raw_input("\nPress Enter to leave Naming... :")
                   successful = 1
                   break 
                elif yesno == "N" or yesno == "n":
                   cls()
                   print """
    
    The existing file called.. """+ long_file_name + """ 
    won't be over-written"""
    
                   moveon = raw_input("""
                   
    Press Enter and try again ... :""")
                   long_file_name = 'No name.ncv'
                   successful = 0
                   pass                 
    #     #
          else:
             successful = 0
    #=============================================================================
    
    # This function enumerates a list of the files found in 'my ncv files',
    # then prints to screen for the user to select and load 1 file.
    
    def getncvList():
        print """
    ======================================================================
    =================   THIS IS THE *.ncv FILE LIST   ==================== 
        """
        ncvlist = os.listdir('c:\\PyNC\\my ncv files')
        itemsindir = len(ncvlist)
        if itemsindir == 0:
            print 'there are no files in my ncv files folder'
            time.sleep(2)
        elif itemsindir >0:
            print 0,ncvlist[0]
            for i in xrange(1,len(ncvlist)):
                c=ncvlist[i]
                print i,c
    #=============================================================================
    # This loads the settings from the file, then displays controlncv.prg.
    
    def userncvChoice():
        print"""
    ======================================================================
    You can just press Enter if you decide not to load a ncv file
        """
        ncvlist = os.listdir('c:\\PyNC\\my ncv files')
        itemsindir = len(ncvlist)
        if itemsindir == 0:
            pass
        elif itemsindir >0:
            userchoice = raw_input("select a file to load, by it's number, then press Enter.. :")
            if userchoice.isdigit():
                number = int(userchoice) # choice is now a real number
                thename = ncvlist[number] # this has selected file's name as a str
                filename = str(thename)
                choice = filename
                with open('c:/PyNC/my ncv files/'+ choice ,'r') as fob:
                    loaded = fob.readlines()
                    fob.close()
                with open('c:/PyNC/my ncv files/'+ choice ,'r') as f:
                    read_data = f.read()
                    f.close
                    b = read_data
                    cls()
                    print """
    You've just loaded the new settings from a ncv;
    If you loaded the wrong file, you'll have to exit here, then,
    come back from the Main Menu to load a different file.
    Below, are the values you loaded.
    """
                with open('c:/PyNC/program files/controlncv.prg','w') as fob:
                     fob.writelines (loaded)
                     fob.close()
                with open('c:/PyNC/program files/updatencv.prg','w') as fob:
                     fob.writelines (loaded)
                     fob.close()
                     print b
    
        else:
             pass
    #=============================================================================
    # This function enumerates a list of the files in the 'import files folder',
    # then prints this to screen for the user to select and load 1 file.
    
    def getimportList():
        print """
    ======================================================================
    ================   THIS IS THE IMPORT FILE LIST   ==================== 
    
    The list below is 'enumerated', so the first number on each line,
    is a file selection number.
    ----------------------------------------------------------------------"""
        ncvlist = os.listdir('c:\\PyNC\\import files')
        itemsindir = len(ncvlist)
        if itemsindir == 0:
            print 'there are no files in the import files folder'
            time.sleep(2)
        elif itemsindir >0:
            print 0,ncvlist[0]
            for i in xrange(1,len(ncvlist)):
                c=ncvlist[i]
                print i,c
    #=============================================================================
    #=============================================================================
    # This loads the import file, then displays contents of controlgcf.prg.
    
    def userimportChoice():
        print"""
    
    ======================================================================
    You can just press Enter if you decide not to import a file
    
        """
        ncvlist = os.listdir('c:\\PyNC\\import files')
        itemsindir = len(ncvlist)
        if itemsindir == 0:
            pass
        elif itemsindir >0:
            userchoice = raw_input("select a file to import, by it's number, then press Enter.. :")
            if userchoice.isdigit():
                number = int(userchoice) # choice is now a real number
                thename = ncvlist[number] # this has selected the file's name as a str
                filename = str(thename)
                choice = filename
                with open('c:/PyNC/import files/'+ choice ,'r') as f:
                    read_data = f.read()
                    f.close
                    b = read_data
                    cls()
                    loaded = b
                    print """\n\n\n\n\n
    the file selected is loaded;\n\n\n
    If you've imported the wrong file, continue to exit from here,\n
    then you can come back from the Main Menu and load another file.\n\n\n
    """
                time.sleep(4)
                with open('c:/PyNC/program files/parsefile.prg','w') as fob:
                     fob.writelines (loaded)
                     fob.close()
        else:
             pass
    #=============================================================================
    #=============================================================================
    #=============================================================================
    #=============================================================================
    
    
    def theParse():
        cls()
        #=========================================================
        # this section below, is to gather all control values for the parse
        # from the controlncv.prg file
    #   #=========================================================
        def ncvzDepth():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[1]  # = usermill depth
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()  # strip the white space here
                    list (dstrip)            # the list(zstrip) has no white space
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit: # check if 1st or 2nd in list is digit
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip() # strip white space from numbers
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
        def ncvPlunge():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[2]
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()
                    list (dstrip)
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit:
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip()
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
        def ncvMill():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[3]
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()
                    list (dstrip)
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit:
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip()
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
        #==============================================================
        def ncvzClear():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[4]
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()
                    list (dstrip)
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit:
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip()
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
        #==============================================================
        def ncvzLift():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[5]
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()
                    list (dstrip)
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit:
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip()
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
        #==============================================================
        def ncvrapiDown():
            with open('c:/PyNC/program files/controlncv.prg','r') as fob:
                getcontrolvalues = fob.readlines()
                fob.close()
                thecontrolncvlist = (getcontrolvalues)
                thencvlist = thecontrolncvlist[6]
                line = "".join (thencvlist)
                dsearch = Find( r' *-*\.*\d\d*\.*\d* *', line)
                if dsearch != "":
                    dstring = (dsearch)
                    dstrip = (dstring).strip()
                    list (dstrip)
                    dword = list (dstring)
                    if dword [0] .isdigit or  dword [1].isdigit:
                        dlistnum = dword [1: ]
                        dstringnum = "".join (dlistnum)
                        dnum = (dstringnum).strip()
                        d = float (dnum)
                        return d
                else:
                    d = " "
                    return d
        #==============================================================
    
        zdepth = ncvzDepth()
        plunge = ncvPlunge()
        mill = ncvMill()
        zclear = ncvzClear()
        zheight = ncvzLift()
        zdownmin = ncvrapiDown()
        #========================
        if zdepth == ' ':
            print 'No Z milling depth found.'
        else:
            print zdepth 
        #========================
        if plunge == ' ':
            print 'No Z plunge speed found.'
        else:
            print plunge
        #========================
        if mill == ' ':
            print 'No X,Y milling speed found.'
        else:
            print mill
        #========================
        if zclear == ' ':
            print 'No Z fixture clearance height found.'
        else:
            print zclear
        #========================
        if zheight == ' ':
            print 'No Z normal lift height found.'
        else:
            print zheight
        #========================
        if zdownmin == ' ':
            print 'No minimum Z rapid down height found'
        else:
            print zdownmin
        #========================
    
        print """
           Above, all ncv values are extracted if they are present
           in the controlncv.prg file.
    
    
           This area is reserved for 'theParse'.
           The 'engine' of the program will go here.
    
           It will be twice as large as the entire program so far.
    
           Where;
           All ncv values are extracted.
           All code line searches are done. 
           All code words and values are extracted.
           All code word arguments will occur.
           All output lines are assembled.
           The output file is written to.
             """
    
    
    
    
    #=============================================================================
    #=============================================================================
    #=============================================================================
    #=============================================================================
    
    def show_instructions():
        print """\n
    =======================================================
    =========    THIS IS THE MAIN PROGRAM MENU    =========\n
    
      Select a process number, then Press Enter, to run it.
              """
        print "  0: Exit the program\n" 
        print "  1: Import a G-code file\n"
        print "  2: Process the G-code file\n"
        print "  3: Check the current settings\n"
        print """  4: 'Create' a new .ncv file  or,
         'Change' any or all
              """
        print "  5: load new config settings from any ncv file\n"
    
    
    #=============================================================================
    # This opens and prints to screen all the current config settings.
    def view():
        with open('c:/PyNC/program files/updatencv.prg','r') as f:
             read_data = f.read()
             f.close()
             a = read_data
             print a
    #=============================================================================
    # This opens the updatencv.prg file and creates the update list
    def Openupdatencv():
        with open('c:/PyNC/program files/updatencv.prg','r') as fob:
           updatencv = fob.readlines()
           fob.close()
           updatelist = (updatencv)
           return updatelist
    
    updatelist = Openupdatencv()
    #=============================================================================
    # main function loop that brings it all together
    def main():
        selection = None
        while selection != "0":
            cls()
            show_instructions()
            selection = raw_input ("\n\nType in an Item number, then Enter, to run it:")
    #=============================================================================
            if selection == "1":
                cls()
                getimportList()
                userimportChoice()
                goback = raw_input ('\n\nPress enter .... Return to Main Menu:')
                if goback == "\n":
                   pass
    #=============================================================================
            elif selection == "2":
                cls()
                theParse()
                goback = raw_input ('\n\nPress enter .... Return to Main Menu:')
                if goback == "\n":
                   pass
    
    #=============================================================================
            elif selection == "3":
                cls()
                print """\n
    =========    THESE ARE THE CURRENT MACHINE SETTINGS    =========\n\n"""
                view()
                goback = raw_input ('\n\nPress enter .... Return to Main Menu:')
                if goback == "\n":
                   pass
    #=============================================================================
            elif selection == "4":
                cls()
                print """\n
    =====================    CHANGE SETTINGS    ======================\n\n"""
                userinPut()
                goback = raw_input ('\n\nPress enter .... Return to Main Menu:')
                if goback == "\n":
                   pass
    #=============================================================================
            elif selection == "5":
                cls()
                print """\n
    ===================    LOAD NEW SETTINGS    =====================\n\n"""
                cls()
                getncvList()
                userncvChoice()
                goback = raw_input ('\n\nPress enter .... Return to Main Menu:')
                if goback == "\n":
                   pass
    #=============================================================================
    
        print "Program closing."
        time.sleep(1)
    main()
    #=============================================================================

  19. #39
    Join Date
    Sep 2009
    Posts
    96
    We'll take a look at some of the aspects of the program.

    At the very top of the program, there is the roadmap for
    the ncv configuration file.
    It is also used to create a blank ncv file.
    The first line is at position 0 in the file and by using
    a header text line, the positions for all the other
    lines becomes more human.
    What is thought of as line 1, is in fact at position 1.
    Notice I've named the line variables with G-code line
    numbers.I kind of helps to make sense of things, especially
    If your used to G-code blocks.
    #================================================= =====
    # variables below are needed to create a blank ncv file
    #================================================= =====
    Code:
    n0 = '  ncv file\n'
    n1 = '  Mill depth    Z      \n'
    n2 = '  plunge speed  Z      \n'
    n3 = '  mill speed   XY      \n'
    n4 = '  clear         Z      \n'
    n5 = '  lift          Z      \n'
    n6 = '  rapid down    Z      \n'
    #================================================= ======

    Below, the blank ncv file is searched for at start up.
    If the file isn't found, the program writes another.
    Notice also, that questioning the program is not direct.
    It's just a matter of;
    'If you agree with me, I want you to give a variable a
    new value, then print something to the screen'.
    'Else, if you don't agree, then do 2 other things for me'.
    After that, the variable 'blankncvisthere' is checked for
    any change, Python may have made.

    Let's say that Python were a person, that for some reason,
    couldn't talk directly to anyone. They may be wearing a mask
    or something that prevents speech.
    You see it in the movies and old TV re-runs, a phrase like;
    'Hey bud!, if you can hear me, raise your finger'

    The variable named 'blankncvisthere', has become Python's
    finger.

    Python isn't much for talking or idle chit chat.

    Code:
    #=======================================================
    # now check on the important files
    print '\nfile check\n'
    time.sleep(0.3)
    #=========================================
    if os.path.exists('c:/PyNC/program files/blankncv.prg'):
        blankncvisthere = 1
        print "blankncv found"
    else:
        blankncvisthere = 0    
        print "blankncv not found"
    if blankncvisthere == 0:
        fob = open ('c:/PyNC/program files/blankncv.prg','w')
        fob.writelines (ncvlines)
        fob.close()
        blankncvisthere = 1
        print 'blankncv file, created'
    time.sleep(0.1)
    #=========================================

    #================================================= ==========================
    Now that there is a blank ncv file, we want to be able to write
    some useful information to it.


    Code:
    #===========================================================================
    #===========================================================================
    def getzDepth():
        with open('c:/PyNC/program files/controlncv.prg','r') as fob:
           thecontrolncv = fob.readlines()
           fob.close()
           updatelist1 = (thecontrolncv)
        print """=============================================================
    =======================     Z DEPTH      ====================\n"""
        print "How deep do you want the Z axis to mill down to ?\n"
        print "\nThe current Z depth is... ", updatelist1[1]
        print """\nIf you just press Enter to skip,
    the current Z depth will remain.
    
        """
        print "Be certain to use a minus for anything below 0(the surface)\n" 
        userzdepth = raw_input("enter a depth, for Z to mill into the surface :")
        nn1 = '  Mill depth    Z      '
        newline = "\n"
        if userzdepth != "\n":
           consolein1 = Userstringsearch( r' *-*\.*\d\d*\.*\d* *', userzdepth )
           if consolein1 != "":
              string1 = (consolein1)
              string1strip = (string1).strip()  # strip any white space here
              if string1strip.isdigit:
                 zdepth = (string1strip)
                 updatelist[1] = nn1 + zdepth + newline
                 print updatelist[1]
                 return updatelist[1]
        else:
           pass
    
    #========================================================
    #========================================================
    The getzDepth() function above opens, controlncv.prg, as a file object.
    Then a variable object named updatelist1 will now point to the values held
    within the file object.
    Now some text is printed to the screen that describes to the user,
    what this part of the program is for and what they need to do.

    userzdepth = raw_input("enter a depth, for Z to mill into the surface :")
    the program will wait until the user types something.

    'nn1' is a variable having the same text as the corresponding ncv line.
    When done, the actual ncv file line is going to be completely overwritten.
    Now a search is made over the input of the user and it shouldn't be a
    surprise to see that it is very similar to the search functions used for picking
    up G-code words from a file line. The user's typed input is after all, text.
    The user's numbers are found then assigned to the variable 'zdepth'.
    Now 3 variables with text are grouped together and their values are assigned
    to the file line number of another variable named 'updatelist'.

    Notice that 'updatelist' is different from 'updatelist1',
    which was the variable pointing to the file object of controlncv.prg, at
    the start of the function to get the Z depth.
    There's a reason for this that should really be as obvious as some guy waving
    a giant red flag, but if you haven't noticed the reason, don't worry it will
    become very clear soon.

    Directly below the group of user input functions,
    we have the 'calls' to each of the functions.
    They are within another function named: userinPut()
    def userinPut():
    So here we have a function calling on many other functions in sequence.
    Our little program is full of them.

    All commands are carried out in the order they are presented.
    Functions and variables when seen, are stored into memory for later use when
    called upon.
    Here's a map of the program structure, as a flowing sequence of events;

    1: the program loads it's modules
    2: store functions;
    : def createPath():
    : def cls():
    : def Userstringsearch():
    : def Find():
    3: store variables for blank ncv and parsefile
    4: store variables for fileisthere
    5: carry out actions from if and else for file checking self.
    6: store functions;
    : def showchngeInstrctns():
    : def getzDepth():
    : def getzplungeSpeed():
    : def getxymillSpeed():
    : def getzClear():
    : def getnormalzLift():
    : def getminzrapiDown():
    : def userinPut():
    : def namemyNcv():
    : def getncvList():
    : def userncvChoice():
    : def getimportList():
    : def userimportChoice():
    : def theParse():
    : def show_instructions():
    : def view():
    : def Openupdatencv():
    7: store variable updatelist = Openupdatencv() # here is updatelist
    : # and it calls Openupdatencv()
    :
    8: store functions;
    : def main():
    9: carry out action ... main()

    We have found 'updatelist'
    A basic rule in programming is that you can't call on a variable or function,
    unless it has first been declared to Python and stored.

    The functions relating to gathering raw_input are only called when the user
    selects Item '4' in the main menu at the very end of the program flow.
    So no attempt has been made to break the rules on calling.

  20. #40
    Join Date
    Sep 2009
    Posts
    96
    In the function... def userinPut():
    we start out with calling... Openupdatencv()
    The program will imediately run the function and open the file;
    'updatencv.prg'

    showchngeInstrctns()
    This prints to screen, simple instructions to the user.
    then it runs each call one after the other;

    getzDepth()
    getzplungeSpeed()
    getxymillSpeed()
    getzClear()
    getnormalzLift()
    getminzrapiDown()

    From there it prints to screen, the 'stop!! load settings' stuff.
    Here if the user types 'y' or 'Y',
    'updatelist' with all the user input, will be written to 2 files;
    'updatencv.prg' and 'controlncv.prg'.
    The config files will now have usable values.

    'updatencv.prg' is the file that we can constantly alter,
    while 'controlncv.prg' is the file from where the program will retrieve
    all configuration values it will use when dealing with code files and will
    continue to use these until altered by the user, using raw_input.

    Some may say, 'I could just go to the file and open it up in notepad, then type
    in whatever values I choose'.
    Yep, sure can, but when the config ncv file has 50 or more lines and some of the
    line descriptions are slightly vague, you run the risk of a small error or typo.

    Just one mistake could lead to a disaster, like break your $$ expensive $$ machine.
    The program's job is to look after the details for us.

    When that's done there is another function call;
    namemyNcv()

    Once again this seems at first glance, to try and break the rules of calling,
    because directly after this we have the function itself;

    # this is for naming a ncv file
    def namemyNcv():

    Be assured that the rules are still not broken.
    The function.. def namemyNcv(): .. was declared long before we could ever
    have entered .. def userinPut():

Page 2 of 3 123

Similar Threads

  1. Read variable with Python
    By albova in forum LinuxCNC (formerly EMC2)
    Replies: 7
    Last Post: 05-26-2012, 12:53 PM
  2. Building a software Indexer
    By bernster in forum Australia, New Zealand Club House
    Replies: 48
    Last Post: 07-08-2011, 07:41 PM
  3. G-code programming library in python
    By bermanmk in forum G-Code Programing
    Replies: 1
    Last Post: 11-10-2009, 03:24 AM
  4. Indexer software
    By Art Ransom in forum Wood Lathes / Mills
    Replies: 4
    Last Post: 07-15-2008, 11:47 PM
  5. just another python gcode thing
    By cyclestart in forum LinuxCNC (formerly EMC2)
    Replies: 8
    Last Post: 02-18-2008, 03:54 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •