how to read the source code of file (.cmd & .tcl )& edit it

A forum for general discussion of the Python programming language.

how to read the source code of file (.cmd & .tcl )& edit it

Postby vishwas » Thu Mar 14, 2013 10:18 am

hiii,
basically i am trying to read and edit the .cmd and .tcl file through python and edit it or place some string words and overwrite the existing code ...pls help urgently i am already delayed in submitting my project..... :?
vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby setrofim » Thu Mar 14, 2013 11:12 am

What code do you have so far?
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby vishwas » Mon Mar 18, 2013 4:45 am

sir this is my python code:-

import re
pat = re.compile('virtex4')

def jojo(mat,dic = {'virtex4':'virtex5'}):
return dic[mat.group()]

with open('C:\Documents and Settings\KSR\Desktop\soth.tcl','rb+') as f:
content = f.read()
f.seek(0,0)
f.write(pat.sub(jojo,content))
f.truncate()

----------------AND THIS MY .TCL CODE NAME SOTH.TCL:----------------------

set projname [lindex $argv 0]


if { [file exists $projname.xise] != 1} then {
project new $projname
puts "creating ise project :$projname "
}
project open $projname

project set family "Virtex4"
project set device "xc4vfx60"
project set package "ff1152"
project set speed "-11"
project set top_level_module_type "HDL"
project set synthesis_tool "XST (VHDL/Verilog)"
##project set simulator "ISim (VHDL/Verilog)"
project set "Preferred Language" "Verilog"
project set "Enable Message Filtering" "false"

xfile add *.vhd

#project set top "Behavioral" "add"

process run "Implement Design"

project close


QUERY-------sir in this i want to change the parameters like from virtex4 to virtex5 and like that in every set preference as if these are in double quotes....they are not changing ...pls help thank you
vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby setrofim » Mon Mar 18, 2013 5:31 am

  • Please use [code ] tags when posting code.
  • Do not open files in update mode; just don't. Read in the content, modify it, then re-open the file for writing and write it back.
  • In your tcl file, "Virtex4" starts with the capital V; in your regex it does not. Regular expressions are (by default) case-sensitive.
  • Since you don't actually specify a regular expression, you could just use string.replace(), but...
  • You probably do want to use a regular expression, since (I'm assuming) you only want to modify the relevant "project set" line and not the rest of the file (where your search term might appear, e.g. as part of a variable name).

Try this:
Code: Select all
import re

SUB_TABLE = {
    'Virtex4': 'Virtex5',
}

FILENAME = 'input.tcl'
REGEX_TEMLATE = r'project set\s+("?[^"]*\S"?)\s+"{0}"'
REPLACE_TEMPLATE = r'project set \1 "{0}"'

if __name__ == '__main__':
    with open(FILENAME) as fh:
        content = fh.read()

    for from_val, to_val in SUB_TABLE.items():
        regex = REGEX_TEMLATE.format(from_val)
        replace_string = REPLACE_TEMPLATE.format(to_val)
        content = re.sub(regex, replace_string, content)

    with open(FILENAME, 'w') as wfh:
        wfh.write(content)


By the way, if I were doing this, I would match the setting's name rather than the setting's value; i.e. rather than saying "substitute Virtex4 with Virtex5", I would say "substitute the value of family with Vertex5". Modifying the code above to do that is left as an exercise for the reader ;)
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby vishwas » Mon Mar 18, 2013 11:56 am

Thank you sir for your reply...i also noticed later that "Virtex4" starts with the capital V that's why i am getting error....sir can i ask you another Q if you don't mind...i am developing a GUI application using python in which i am facing a problem in this i am trying to create a button & after clicking it ...it makes the copy of the file of soth.tcl which is stored in another location ....into the new folder created ...now pls see this code:-

Code: Select all
[color=#40BFBF]
from Tkinter import *
import os
import tkMessageBox
import shutil
import re
global newpath

prr=Tk()
prr.title("RCS TOOL")
prr.geometry('700x700+700+700')
var = StringVar()
var.set("Project Name")
label=Label( prr,textvariable=var,height=3)
label.config(font=('arial',11))
label.place(x=100,y=10)

name_entry=Entry(prr)
name_entry.place(x=200,y=30)


def new_proj():
   
    newpath = r"C:\Documents and Settings\KSR\Desktop\%s"%name_entry.get()
    if not os.path.exists(newpath): os.makedirs(newpath)

    shutil.copy2('C:\Documents and Settings\KSR\Desktop\myproj\soth.tcl',newpath)

newpath=newpath+"\soth.tcl"
pat = re.compile('virtex4')
var1=StringVar()

def new_value(mat,dic = {'virtex4':'virtex5'}):
    return dic[mat.group()]

with open(r'newpath','rb+') as f:
    content = f.read()
    f.seek(0,0)
    f.write(pat.sub(new_value,content))
    f.truncate()
   

b1= Button(prr,newpath,text="create new project",padx=10,pady=3,command=new_proj)
b1.place(x=330,y=25)

prr.mainloop()  [/color]



NOW-In this its showing an error of newpath is not declared or if i declare global it says -"global name 'newpath' is not defined".....what to do.... :roll: :?:......and sir pls copy the .tcl file which i posted before....of that file i am making copy into the new folder and its not editing there.... :(
vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby setrofim » Mon Mar 18, 2013 1:17 pm

In the future, if you have a question that is unrelated to the previous issue, please start a new topic rather than posting in the same thread.

Python complains because the first declaration of newpath is inside the new_proj() function. This means that it is not available outside of that function, so when your code says
Code: Select all
newpath=newpath+"\soth.tcl"

in the global scope, Python can't resolve the newpath on the right of the =. To get rid of the error, move the original declaration of newpath from the global scope.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby vishwas » Tue Mar 19, 2013 4:30 am

move the original declaration of newpath from the global scope....means ????......sir i dnt understand can you tell me more or explain me through the code exactly how to declare it and where should i do the correction and sir the code
Code: Select all
with open(r'newpath','rb+') as f:


do you think this syntax is correct to read the file with new path ....

......and sorry ...i will from now post it from the new thread ....thank you a lot.... :|
vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby setrofim » Tue Mar 19, 2013 6:34 am

vishwas wrote:move the original declaration of newpath from the global scope....means ????......

Sorry, I just meant put it outside of the new_proj function.

vishwas wrote:
Code: Select all
with open(r'newpath','rb+') as f:


do you think this syntax is correct to read the file with new path ....

Almost. You want to be using the newpath variable, not the literal string 'newpath', But, as I've said before, using the 'rb+' mode is a really bad idea. You open the file separtely for reading and writing.

Here is is the updated code:
Code: Select all
import os
import re
import shutil
from Tkinter import *

SUB_TABLE = {
    'Virtex4': 'Virtex5',
}

FILEPATH = 'input.tcl'
NEWPATH = 'new_location'
REGEX_TEMLATE = r'project set\s+("?[^"]*\S"?)\s+"{0}"'
REPLACE_TEMPLATE = r'project set \1 "{0}"'


def new_proj():
    if not os.path.exists(NEWPATH):
        os.makedirs(NEWPATH)
    shutil.copy2(FILEPATH, NEWPATH)

    new_filepath = os.path.join(NEWPATH, os.path.basename(FILEPATH))

    with open(new_filepath) as fh:
        content = fh.read()

    for from_val, to_val in SUB_TABLE.items():
        regex = REGEX_TEMLATE.format(from_val)
        replace_string = REPLACE_TEMPLATE.format(to_val)
        content = re.sub(regex, replace_string, content)

    with open(new_filepath, 'w') as wfh:
        wfh.write(content)


if __name__ == '__main__':
    prr=Tk()
    prr.title("RCS TOOL")
    prr.geometry('700x700+700+700')
    var = StringVar()
    var.set("Project Name")
    label=Label( prr,textvariable=var,height=3)
    label.config(font=('arial',11))
    label.place(x=100,y=10)

    name_entry=Entry(prr)
    name_entry.place(x=200,y=30)

    b1= Button(prr,text="create new project",padx=10,pady=3,command=new_proj)
    b1.place(x=330,y=25)

    prr.mainloop()
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby vishwas » Tue Mar 19, 2013 11:39 am

Thank you very much for the help....but sir i am kind a novice to the python programming...so i am not able to understand it fully... :oops: :cry: ...
sir basically in my program a GUI application i am creating in which there is a entry widget which create the name of the folder given by the user and a button called "new project"
which after clicking or triggering it .....it first create a folder on name of the user entry and then makes a copy of the soth.tcl file into the folder and make edits like virtex4 to virtex5 and so on for other parameters......now in your code.....regex_temlate and replace_template ????...("if you can give me the code which i can directly copy and paste it than it will be vollaaaa..... :mrgreen: ).....by the way thanks a lot for giving your precious time...
vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby setrofim » Tue Mar 19, 2013 11:54 am

vishwas wrote:Thank you very much for the help....but sir i am kind a novice to the python programming...so i am not able to understand it fully... :oops: :cry: ...

Go through this.

vishwas wrote:now in your code.....regex_temlate and replace_template ????...

You want to make string substitutions in (tcl) code. This is not a safe thing to do, since the string you are substituting may appear in places you wouldn't expect, and then the code will no longer work. The regular expression are used to give context to the substitutions -- so the substitution will only happen inside "project set" clauses, and not elsewhere in the code. The templates are used to create regular expressions and substitute values for specific parameters.

vishwas wrote: if you can give me the code which i can directly copy and paste it than it will be vollaaaa..... :mrgreen:

No. I am not going to do your work for you. This forum is here to help you learn, not provide free tech support. If you really want some to write the code for you, make a request on the jobs forum and offer payment.
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: how to read the source code of file (.cmd & .tcl )& edit

Postby vishwas » Thu Apr 04, 2013 2:43 am

hi sir thanks the code is working but still i am facing a little problem in it...:-
Code: Select all
import os
import re
import shutil
from Tkinter import *

SUB_TABLE = {
    'Virtex4': 'Virtex5', #------->and here also i want user input from the drop box menu..... :roll:
}

FILEPATH =(r'C:\Users\vishwas\Desktop\soth.tcl')
NEWPATH =(r"C:\Users\vishwas\Desktop\%s")%name_entry.get()  #---------->>>>>at this point it saying name_entry.get() is not                         
                                                                                                    defined bcoz i am declaring entry widget   
                                                                                                    later...how to resolve this now  :x
REGEX_TEMLATE = r'project set\s+("?[^"]*\S"?)\s+"{0}"'
REPLACE_TEMPLATE = r'project set \1 "{0}"'


def new_proj():
    if not os.path.exists(NEWPATH):
        os.makedirs(NEWPATH)
    shutil.copy2(FILEPATH, NEWPATH)

    new_filepath = os.path.join(NEWPATH, os.path.basename(FILEPATH))

    with open(new_filepath) as fh:
        content = fh.read()

    for from_val, to_val in SUB_TABLE.items():
        regex = REGEX_TEMLATE.format(from_val)
        replace_string = REPLACE_TEMPLATE.format(to_val)
        content = re.sub(regex, replace_string, content)

    with open(new_filepath, 'w') as wfh:
        wfh.write(content)


if __name__ == '__main__':
    prr=Tk()
    prr.title("RCS TOOL")
    prr.geometry('700x700+700+700')
    var = StringVar()
    var.set("Project Name")
    label=Label( prr,textvariable=var,height=3)
    label.config(font=('arial',11))
    label.place(x=100,y=10)

    name_entry=Entry(prr)
    name_entry.place(x=200,y=30)

    b1= Button(prr,text="create new project",padx=10,pady=3,command=new_proj)
    b1.place(x=330,y=25)

    prr.mainloop()


vishwas
 
Posts: 14
Joined: Thu Mar 14, 2013 9:57 am


Return to General Discussions

Who is online

Users browsing this forum: Exabot [Bot] and 2 guests

cron