Python script integration in SCOM - Example needed?

Hello,
I've been googling around a lot looking for an example of Python script integrated with SCOM. I understood that is possible, but I only find example for PowerShell or VisualBasic (for instance here >> http://opsit.blogspot.hk/2013/11/scom-scripting-basics.html
). This link looks great for what I need, but it's not coded in Python.. :-(
I'm not a native programmer so I'm struggling in reading VisualBasic/PowerShell code and trying to understand how to do the same in Python. Even a simple example of Python+SCOM integration would be of great help in understanding how it works in terms
of libraries to include and input/output between the systems.
Can you point me towards any example of Python+SCOM integration?
Thanks in advance.
W.

Hi,
I would prefer to rewrite your library in Powershell as it is fully supported by SCOM and you also get Powershell Know-How which is always fine :).
A good starting point is always the Python Developers Guide to Powershell ;)
http://mohd-akram.github.io/2013/05/16/a-python-developers-guide-to-powershell
Please find below some Articles about Invoke-Restmethod in Powershell:
http://technet.microsoft.com/en-us/library/hh849971.aspx
http://blogs.technet.com/b/heyscriptingguy/archive/2013/10/21/invokerestmethod-for-the-rest-of-us.aspx
Update: If you want to keep you Python Script you still could write a Wrapper Function for it in Powershell:
https://craigwwright.wordpress.com/2009/05/31/running-python-scripts-inside-windows-power-shell/
Cheers,
Christoph
Blog:
http://blog.cmaresch.at/ 
Twitter:
  LinkedIn:
  XING:
Note: Posts are provided “AS IS” without warranty of any kind, either expressed or implied, including but not limited to the implied warranties of merchantability and/or fitness for a particular purpose.

Similar Messages

  • Need help running a Python script when DVD inserted

    We had an intern that created a custom Python script to rip our old event recording DVDs back to a digital format. The script creates a JSON description file and asks a set of questions to create the metadata in the JSON file (e.g. Date of event).
    The way the intern set this up was that you'd click on the Python script which would open a terminal window where you fill in the metadata. It then asks if the DVD is in the computer. At this point you place the DVD in. A few seconds later, the Python script notices the DVD and proceeds to rip the DVD at our specific file size requirements along with the inputted metadata.
    We then upgraded the Mac from Mountain Lion to Lion and the script stopped working. Our intern has since left. I have now moved the Python script onto my Mountain Lion Mac. The intern's last message to me was that he had written an AppleScript that ran when the DVD was inserted which then referred to the Python script. The intern has since stopped replying to emails.
    This is a very important project that I would like to continue. Any help would be greatly appreciated!

    well, oddly, that should never have worked. 
    Try this:  open the applescript editor, copy in the following line:
    tell application "Terminal"
              do script "python /Users/medialab/dvddrip rename"
              activate
    end tell
    Save it, making sure that the 'File Format' pull down says Script (the new file will have a '.scpt' extension). You'll be able to select that file in the cd/dvd preferences.
    I assumed that you wanted this to open in terminal so that you can enter options on the command line. If that's not correct, let me know.

  • Need help with python script for Deluge

    I am using Deluge 1.3.2 with web server, and all works fine, I use this script in the Deluge settings to execute upon torrent completion:
    #!/bin/bash
    torrentid=$1
    torrentname=$2
    torrentpath=$3
    torrenttimedelta=`/usr/bin/python2 /home/bobby/scripts/deluge/torrentTimeDelta.py $1`
    subject="Started download new torrent!"
    message="$torrentname to $torrentpath"
    echo -e `date`"::Finished downloading torrent:$2 in: $3" with id:$torrentid >> ~/logs/scripts.log
    echo -e `sendEmail -t [email protected] -f [email protected] -u "deluge server notification: torrent $torrentname is complete!" -m "$torrentname has completed downloading at: $torrentpath and took $torrenttimedelta to complete :)" -xu [email protected] -xp password -v -o tls=yes -s email.com` >> ~/logs/scripts.log
    echo ---------------------------------------- >> ~/logs/scripts.log
    This is to email me when a torrent is done and works. What I wanted to add to this email was the time taken to complete the torrent. I have gotten help from Deluge forum in this thread: http://forum.deluge-torrent.org/viewtop … =9&t=36989  However I think it's something with Python within Arch that is the obstacle, and so that helpful person can't do much more IMO. The python script I'm using is:
    #!/usr/bin/python2
    from deluge.ui.client import client
    from twisted.internet import reactor
    d = client.connect()
    def on_connect_success(result):
    print "Connection was successful!"
    def on_get_torrent_value(value):
    for torrent in value:
    print "%s: %s" % (torrent, value[torrent]["name"])
    client.disconnect()
    reactor.stop()
    client.core.get_torrents_status({}, ["name"]).addCallback(on_get_torrent_value)
    d.addCallback(on_connect_success)
    def on_connect_fail(result):
    print "Connection failed!"
    print "result:", result
    d.addErrback(on_connect_fail)
    reactor.run()
    Now if I call this from shell directly, it works. However, including it with my email script at the top, Deluge itself freezes and no email is sent. I run ps aux | grep deluge and I can see that the script has run, but apparently died and all is just hanging. I kill the script process and Deluge resumes just fine, the email is sent. Kinda confused how to remedy this, appreciate any help Thanks
    P.S. When I get the email, the part that says ""$torrentname has completed downloading at: $torrentpath and took $torrenttimedelta to complete "" shows nothing where $torrenttimedelta should be, it just says "and took to complete"

    [edit]  Sorry, I don't use deluge and I messed up my test script. If the script is executable try `/home/bobby/scripts/deluge/torrentTimeDelta.py $1`
    Are there any other errors? or try running bash with debug output to see if it will tell you something else
    The problem you are having is bash doesn't recognize variables inside the tick marks.
    Hope that helps
    Last edited by rickeyski (2011-07-05 19:27:36)

  • Python script in dasylab using single input multiple output

    Hello
    For a project, I would like to use the python scripting module of dasylab 13. I got it to work for simple functions such as y=f(x), where i have one input and one output.
    The next step in order to get to where i want to be with my script is using a single input and generating two outputs.
    I defined it in the "predefined settings" that pops up first. The module created looked as it should, having one input and two outputs. However, when I wanted to edit the script (and double clicked the module) the module went back to having one input and one output.
    I searched the help and found the section "channel assignment constants". There describe the various constants, which should have been set in predefined settings. In my case it is CR_1_2.
    It also states to setup the meta data in the SetupFifo tab.
    Now here is my problem: How should i change the SetupFifo tab?
    I tried the command:
    self.SetChannelRelation(channel_no, Ly.CR_1_2)
    Unfotunately this didn't work, which doesn't supprise me, as I made this command up, based on the examples in the help file on the SetupFifo tab. Those are, however, for SetChannelFlags and SetChannelType, which I don't think I need yet...
    Has anyone experienced a similar problem? I also installed a trial version on another computer to check if it works there (it doesn't).
    Or does someone know a method to find out how to be able to change inputs and outputs the way i want?
    Every help will be greatly appreciated.
    Sincerely, Jarno

    You do not need to set the channel relation for "simple" channel relation like 1:2, 2:1, etc.
    Just set the relation you want in the configration dialog that open when you drop a script module into to worksheet.
    The channel relation and their python constants have nothing to do with the amount of inputs and outputs of a script module.
    The channel relation tells the "DASYLab core" how to guide meta data (channel names, units, etc) through a module.
    In function "DlgInit" you have to tell DASYLab how many inputs and outputs your module should have.
    Your module should have 2 outputs for each input: this combination of input and outputs is called a "channel".
    Because one channel has 2 outputs, the module can have max. 8 channels only.
    The dialog with the channelbar "thinks" in  channels, but DASYLab "thinks" in connectors (connectors are inputs/outputs).
    So, you are responsible to translate "channels" in "connectors" and vice versa
    In DlgInit you can ask DASYLab about the amount of inputs and outputs.
    self.NumInChannel <-- amout of connectors on modules left side
    self.NumOutChannel <-- amount of connectors on the right side
    self.DlgNumChannels <-- amount of activated channels in the dialog (something between 1 and DlgMaxChannels)
    Your module's channels have 1 input, 2 outputs each, so you can write either
    self.DlgNumChannels = self.NumOutChannel / 2
    or
    self.DlgNumChannels = self.NumInChannel
    If the module has 3 input and 6 outputs, the dialog will get 3 channels.
    In DlgOk you need to translate the amount of channels into the correct amount of connectors (inputs/outputs):
    For "one channel = 1 input + 2 outputs" this is:
    self.SetConnectors( self.DlgNumChannels, self.DlgNumChannels * 2 )
    DlgInit
    self.DlgNumChannels = self.NumInChannel
    # or: self.DlgNumChannels = self.NumOutChannel / 2
    self.DlgMaxChannels = 8 # or Ly.MAX_CHANNELS/2
    DlgOk
    self.SetConnectors( self.DlgNumChannels, self.DlgNumChannels * 2 )
    M.Sc. Holger Wons | measX GmbH&Co. KG, Mönchengladbach, Germany | DASYLab, DIAdem, LabView --- Support, Projects, Training | Platinum National Instrument Alliance Partner | www.measx.com

  • Merge Python Script

    Does anyone have any ideas about creating a Python script to merge some pdfs and possibly sign the finished document? I've looked at pyPdf.pdf a little. Not sure if this is the best way to go or not. Just need help getting started. Examples might be helpful.
    I'm leery of JavaSciprt b/c of security issues.
    Any advice, comments or criticisms are welcome.
    Thanks!

    Adobe has addressed all of those issues.
    Users need to apply update their products and update their products.
    Acrobat X has a sandbox feature that really restricts Acrobat/Reader from the OS.

  • Running python script with system arguments from applescript

    Hi,
    I am trying to run a python code from within applescript. A string should be passed as an argument to the python script, i.e. from the terminal, I would do the following
    cd /Users/thatsme/Library/Scripts/myfolder
    python my_python_file.py abcdefg
    There are two ways I figure I could do this in applescript. "abcdefg" are contained in the variable strNote
    a) directly:
    do shell script "cd /Users/thatsme/Library/Scripts/myfolder; python my_python_file.py " & strNote
    b) calling Terminal
    tell application "Terminal"
      activate
              do script "cd /Users/claushaslauer/Library/Scripts/OO_latex; python my_python_file.py " & strNote
    end tell
    I would prefer option a) as I don't really want to have Terminal windows popping up. The strange thing is, that I see in the applescript results window the result of the print statements in the python script, but no output is generated (the python script contains a few os.system() commands.
    Option b) does what it is supposed to be doing, however, applescript does not wait until the script is finished running.
    Why does option a) nor work, and what do I need to change to make it work?

    Thank you guys for your help, this is really weird.
    Here is my full applescript
    set strNoteQ to "1+1=2"
    (* for whatever reason, this does not work *)
    do shell script "cd /Users/claushaslauer/Library/Scripts/OO_latex; python create_latex_pdf.py " & strNoteQ
    Below is my python skript.
    When I call it as
         python create_latex_pdf.py 1+1=2
    it creates a wonderful pdf.
    With the applescript above, it prints the print statements, it also generates the latex file temp.tex -- correctly, so I assume the string in this example is ok.
    However, it does not execute the latex related commands (the three os.system calls)
    Is it not a good idea / not possible to execute os.system in a python script that is called from applescript? <sorry if I had brought all the attention to the string issue>
    here is the python script:
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import sys
    import os
    import datetime
    import time
    def main():
        str_latex_note = sys.argv[1]
        print "%s" %  str_latex_note
        preamble = """\documentclass{article}
    \usepackage{amsmath,amssymb}
    \pagestyle{empty}
    \\begin{document}
    {\huge
    %s
    \end{document}"""% (str_latex_note)
        ## write latex file
        cur_path = r'/Users/mypath/Library/Scripts/OO_latex'
        cur_file = "temp.tex"
        fobj = open(os.path.join(cur_path, cur_file), 'w')
        fobj.writelines(preamble)
        fobj.close()
        ## process latex file
        print cur_path
        os.chdir(cur_path)
        cmd = 'latex temp.tex'
        print cmd
        print "running latex"
        os.system(cmd)
        cmd2 = 'dvips -E -f -X 1200 -Y 1200 temp.dvi > temp.ps'
        print "running dvips"
        os.system(cmd2)
        cmd3 = 'epstopdf temp.ps'
        print "running epstopdf"
        os.system(cmd3)
        print "done!"
    if __name__ == '__main__':
        main()

  • How to call Python Scripts throght Labview

    Hi all,
    I am new to this community. Need some inputs  for following Questions
    Questions:
    1)  How can I call python script from LabView?
     (Basically this python script calls some other DLL and print some message, to run the script using Python net in my application .To run my script in python net using following commands: import python script name )
    2)  In how many ways we can call Python scripts from labview?
    I have tried with this option "System Exec.vi "in labview , able to calling pythonnet but unable to send commands and arguments to run python script(i.e  import python script name ). 
     If anyone have samples".VI " please send to me. If you people want any information and clarification  from my side please let me know. Thanks in advance.
    Regards,
    Sambasivareddy

    One way is to create a client server app and to send arguments to python (and back) over TCP/IP. This work very well.
    There is an example on the old OpenG Website about this. Look it up.
    Python client to LabVIEW Server.
    PJM
    Message Edited by PJM_Labview on 03-12-2008 09:00 AM
    Got EasyXML?
    JKI.VIPM.EasyXML.OpenG.LAVA.Builder.blog

  • Passing arguments to and running a Python script

    I have a Python script that I am creating a Java GUI for. How can I call this python script from within Java? I need to pass three arguments to the script, each one a string. Are Jepp / Jython what I need to use? Any tips for an absolute beginner at Java / Python integration?

    Yes, after you create the PythonInterpreter, you can just call set on it and those objects are then directly accessible in the jython scripts. To run blocks of code, I've been doing something like
    //after initialize and set interpreter vars
    PyObject locals = pythonInterpreter.getLocals();
    PyCode code = Py.compile_flags(source, filename, "exec", null);
    Py.exec(code, locals, locals);Note though that this was on Jython 2.1 or 2.2 a while back, so you might have a newer version with maybe not exactly the same method calls.
    cheers, Brynjar

  • Run Python Script in Automator

    I have a python script (which was written for me), and I would like to make it so that the script executes every x minutes. I know this should be simple to do, but I can't figure it out.
    Thus far, I have created a workflow in automator, used the "Run Shell Script" action, and pasted the script into the text field.
    "Workflow failed - 1 error
    I'm very new to this, so I'm sure it's a simple error. Any help would great.
    Here is the script I am trying to execute.
    #!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
    # you can change the above line to point to the location of python
    # on your system (you can check this by typing 'which python' into
    # Terminal.app), but this isn't necessary if you execute the script
    # using "python ksl.py [URL]"
    # change the value of NAME to your desired name
    NAME = "Bob Jones"
    # change the value of EMAIL to your desired email
    EMAIL = "[email protected]"
    # your message will be the contact name as mined from the page source,
    # followed by whatever message you enter between the following triple quotes
    MESSAGE = """Replace this text with your message. Newlines are also OK."""
    import mechanize
    import re
    import sys
    def setupBrowser(url):
    b = mechanize.Browser()
    # b.sethandlerobots(False)
    # b.addheaders = [('User-agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)')]
    try:
    b.open(url)
    except mechanize._mechanize.BrowserStateError:
    print >> sys.stderr, "You have mistyped the URL. It must by in the following format, including the quotes and the preceding 'http://':\n\t %s [--test] 'http://www.blah.com'" % (sys.argv[0])
    sys.exit(1)
    return b
    def grabLinks(b):
    """Takes in a mechanize.Browser() object pointed to a listings URL and returns a listing of classified ad links."""
    links = []
    for link in b.links():
    # change this line if the URL format ever changes
    if re.search(r'&ad=', link.url):
    links.append(mechanize.urljoin(link.base_url, link.url))
    return links
    if _name_ == '_main_':
    # check for proper command line args
    if len(sys.argv) != 2 and len(sys.argv) != 3:
    print >> sys.stderr, "Usage: %s [--test] url" % (sys.argv[0])
    sys.exit(1)
    args = sys.argv[1:]
    if len(args) == 1:
    # start from listings page
    url = args[0]
    # set up the mechanize browser object
    b = setupBrowser(url)
    # grab only the relevant ad links
    links = grabLinks(b)
    if not links or len(links) == 0:
    # the links do not follow the same format as the original page
    print >> sys.stderr, "The link format has changed, or you have mistyped the URL."
    sys.exit(1)
    # open the first link on the listings page
    b.open(links[0])
    else:
    # start from a single listing
    if args[0] != "--test":
    print >> sys.stderr, "Usage %s [--test] url"
    sys.exit(1)
    url = args[1]
    b = setupBrowser(url)
    # grab the HTML so that we can search for the contact name
    response = b.response().get_data()
    # perform a regex search on the HTML for the contact name
    regexSearch = re.search(r'Contact Name:\s*\s(w+)s', response)
    contactName = ""
    if regexSearch:
    # contact name found -- store it
    contactName = regexSearch.group(1)
    else:
    # contact name not found -- use generic greeting
    contactName = "Hello"
    theOne = ""
    # find the "Email Seller" link (stored as "theOne")
    for link in b.links():
    # again, if the URL changes, change this line
    if re.search(r'xmldb=', link.url):
    theOne = mechanize.urljoin(link.base_url, link.url)
    if theOne == "":
    # something went wrong
    print >> sys.stderr, "'Email Seller' link has changed formats within the HTML."
    sys.exit(1)
    b.open(theOne)
    # fill out the forms. note that I am grabbing the SECOND form here.
    # again, this might change over time, so feel free to change this from
    # nr=1 to nr=0 (for the first form), nr=2 (for the third form), etc.
    b.select_form(nr=1)
    b['form_4'] = NAME
    b['form_5'] = EMAIL
    # append the contact name to the rest of the message
    MESSAGE = contactName + """,\n\n""" + MESSAGE
    b['form_6'] = MESSAGE
    # submit the form
    b.submit()
    b.close()

    If the script works, and all you need is to execute every x minutes, use launchd, and its simple to write with the Lingon GUI: http://sourceforge.net/projects/lingon/files/

  • Python script to parse 'iwlist scan' into a table

    Hi,
    I've written a small python script that parses the output of the command "iwlist interface scan" into a table.
    Why ?
    Like many arch linux users I think, I use netcfg instead of something like network manager or wicd. So the most natural way to scan for wifi networks in range is iwlist scan. But the output of this command is huge and I find it difficult to retrieve information. So this script parses it into a table : one network, one line.
    Example output
    Name Address Quality Channel Encryption
    wifi_1 01:23:45:67:89:AB 100 % 11 WPA v.1
    wifi_2 01:23:45:67:89:AC 76 % 11 WEP
    wifi_3 01:23:45:67:89:AD 51 % 11 Open
    wifi_4 01:23:45:67:89:AE 50 % 11 WPA v.1
    wifi_5 01:23:45:67:89:AF 43 % 4 Open
    wifi_6 01:23:45:67:89:AG 43 % 4 WPA v.1
    Details
    It reads from stdin so you use it like that: iwlist wlan0 scan | iwlistparse.py
    The width of the columns is determined by what's in it.
    You can easily do a bit more than just parsing the info: in the example above, the quality has been calculated to percents from a ratio (e.g. 46/70).
    It is sorted, too.
    Customization
    It's python so it's easy to customize. See the comments in the code.
    Code
    #!/usr/bin/env python
    # iwlistparse.py
    # Hugo Chargois - 17 jan. 2010 - v.0.1
    # Parses the output of iwlist scan into a table
    import sys
    # You can add or change the functions to parse the properties of each AP (cell)
    # below. They take one argument, the bunch of text describing one cell in iwlist
    # scan and return a property of that cell.
    def get_name(cell):
    return matching_line(cell,"ESSID:")[1:-1]
    def get_quality(cell):
    quality = matching_line(cell,"Quality=").split()[0].split('/')
    return str(int(round(float(quality[0]) / float(quality[1]) * 100))).rjust(3) + " %"
    def get_channel(cell):
    return matching_line(cell,"Channel:")
    def get_encryption(cell):
    enc=""
    if matching_line(cell,"Encryption key:") == "off":
    enc="Open"
    else:
    for line in cell:
    matching = match(line,"IE:")
    if matching!=None:
    wpa=match(matching,"WPA Version ")
    if wpa!=None:
    enc="WPA v."+wpa
    if enc=="":
    enc="WEP"
    return enc
    def get_address(cell):
    return matching_line(cell,"Address: ")
    # Here's a dictionary of rules that will be applied to the description of each
    # cell. The key will be the name of the column in the table. The value is a
    # function defined above.
    rules={"Name":get_name,
    "Quality":get_quality,
    "Channel":get_channel,
    "Encryption":get_encryption,
    "Address":get_address,
    # Here you can choose the way of sorting the table. sortby should be a key of
    # the dictionary rules.
    def sort_cells(cells):
    sortby = "Quality"
    reverse = True
    cells.sort(None, lambda el:el[sortby], reverse)
    # You can choose which columns to display here, and most importantly in what order. Of
    # course, they must exist as keys in the dict rules.
    columns=["Name","Address","Quality","Channel","Encryption"]
    # Below here goes the boring stuff. You shouldn't have to edit anything below
    # this point
    def matching_line(lines, keyword):
    """Returns the first matching line in a list of lines. See match()"""
    for line in lines:
    matching=match(line,keyword)
    if matching!=None:
    return matching
    return None
    def match(line,keyword):
    """If the first part of line (modulo blanks) matches keyword,
    returns the end of that line. Otherwise returns None"""
    line=line.lstrip()
    length=len(keyword)
    if line[:length] == keyword:
    return line[length:]
    else:
    return None
    def parse_cell(cell):
    """Applies the rules to the bunch of text describing a cell and returns the
    corresponding dictionary"""
    parsed_cell={}
    for key in rules:
    rule=rules[key]
    parsed_cell.update({key:rule(cell)})
    return parsed_cell
    def print_table(table):
    widths=map(max,map(lambda l:map(len,l),zip(*table))) #functional magic
    justified_table = []
    for line in table:
    justified_line=[]
    for i,el in enumerate(line):
    justified_line.append(el.ljust(widths[i]+2))
    justified_table.append(justified_line)
    for line in justified_table:
    for el in line:
    print el,
    print
    def print_cells(cells):
    table=[columns]
    for cell in cells:
    cell_properties=[]
    for column in columns:
    cell_properties.append(cell[column])
    table.append(cell_properties)
    print_table(table)
    def main():
    """Pretty prints the output of iwlist scan into a table"""
    cells=[[]]
    parsed_cells=[]
    for line in sys.stdin:
    cell_line = match(line,"Cell ")
    if cell_line != None:
    cells.append([])
    line = cell_line[-27:]
    cells[-1].append(line.rstrip())
    cells=cells[1:]
    for cell in cells:
    parsed_cells.append(parse_cell(cell))
    sort_cells(parsed_cells)
    print_cells(parsed_cells)
    main()
    I hope you find it useful. Please report bugs, I haven't tested it a lot. You may have to customize it though, because I think not all iwlist scan outputs are the same. Again, see comments, it should be easy.

    This tool is very helpfull. I am trying to add a new function to the existing code to parse the signal level parameter from the output of iwlist wlan0 scan, but I am getting lot of issues .Since I am new to python script can anyone help me to extract the signal level also from the scan put put.
    The parametr to be used is Signal level=-44 dBm ,I am trying to create a one more column with Signal level and print its out in the table.
    Example:-
    Signal level
    -44db
    The error I am getting
      File "iwlist_parser_Testing.py", line 146, in <module>
        main()
      File "iwlist_parser_Testing.py", line 144, in main
        print_cells(parsed_cells)
      File "iwlist_parser_Testing.py", line 123, in print_cells
        print_table(table)
      File "iwlist_parser_Testing.py", line 102, in print_table
        widths=map(max,map(lambda l:map(len,l),zip(*table))) #functional magic
      File "iwlist_parser_Testing.py", line 102, in <lambda>
        widths=map(max,map(lambda l:map(len,l),zip(*table))) #functional magic
    TypeError: object of type 'NoneType' has no len()
    Could some pls help me to solve this issue
    Thanks

  • Call an ABAP program or a function module from command prompt/python script

    Dear All,
    I want to call a function module/ABAP program from command prompt or a python script.
    Let me explain with an example.
    There is a function module "z_add" that takes  two integers as input parameters and generates their sum.
    the sum is the output parameter.
    Now i want to call this function module from command prompt / python script and pass parameters to this function module.
    In return i must get the sum(i.e. the output of function module).
    I tried using STARTRFC ,was able to call the FM but could not get the return value(output) from FM.
    Can you please provide me the code of such a function module and the method to call it thereby passing parameters and getting the sum.
    Thanks and regards,
    Gaurav
    Edited by: gauravkec2005 on Mar 4, 2010 7:41 AM

    thank you both!  helpful answers! :o)
    anyway! 
    i have written the program which is called from the SAPScript:
        /:       PERFORM GET_VATNUMBER IN PROGRAM ZFI_F140_OPERATIONS
        /:       USING &BKPF-BUKRS&
        /:       CHANGING &VATNUMBER&
        CE       VAT Registration No : &VATNUMBER&
        REPORT zfi_f140_operations.
        FORM get_vatnumber TABLES in_par  STRUCTURE itcsy
                                  out_par STRUCTURE itcsy.
          DATA: lv_co_code TYPE bukrs,
                lv_vat_no  TYPE stceg.
          READ TABLE in_par WITH KEY name = 'BKPF-BUKRS'.
          MOVE in_par-value TO lv_co_code.
          SELECT SINGLE stceg FROM t001
            INTO lv_vat_no WHERE bukrs = lv_co_code.
          out_par-name = 'VATNUMBER'.
          WRITE lv_vat_no TO out_par-value.
          CONDENSE out_par-value.
          MODIFY out_par INDEX 1.
        ENDFORM.              
    it is not working and i cannot work out why... 
    i have not been ABAPing for very long but have had a go.... 
    any thoughts as to what i have done wrong?
    or point me where i should be looking?  thank you!

  • Include python script inside an app

    Hi all, I'm writing an applescript app which should use a python script.
    how can I include the script inside the apple and have it called by the applescript?
    Thank you!

    Now, is there a way to let the user choose both the output file directory and the output file name (out.iso)?
    To get the filename, add this after the code to select the directory:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    font-weight: normal;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #E6E6EE;
    overflow: auto;">
    set outPutName to text returned of (display dialog "Now, please enter a filename:" default answer "out" with title "Enter Filename") & ".iso"</pre>
    But you need to remove "quoted form of the" from dirOutput.
    Also, "set dirOutput to POSIX path of the dirOut" is not needed.
    so, this should work:
    <pre style="
    font-family: Monaco, 'Courier New', Courier, monospace;
    font-size: 10px;
    font-weight: normal;
    margin: 0px;
    padding: 5px;
    border: 1px solid #000000;
    width: 720px;
    color: #000000;
    background-color: #E6E6EE;
    overflow: auto;">
    set dirOut to (POSIX path of (choose folder with prompt "Scegli la posizione in cui salvare il file convertito"))
    set outPutName to text returned of (display dialog "Now, please enter a filename:" default answer "out" with title "Enter Filename") & ".iso"
    if outPutName is ".iso" then set outPutName to "out.iso" -- simple error check for blank name
    if outPutName contains "/" then set outPutName to "out.iso" -- simple error check for bad charater in name
    set fullPathOut to quoted form of (dirOut & outPutName)
    </pre>
    Tony

  • Calling Python Script from LabVIEW

    Hello Everyone,
    I want to call the Python script from LabVIEW.
    I tried with using at the command line but i am unable to run that script file..
    i have gone through LabPython but i am unable to call the scripts from there also..
    If someone has an example of a VI which invokes a python script, it will be very helpful...
    Thanks a lot in advance
    Regards
    Avni

    avni wrote:
    I have to invoke the Script file at command prompt.
    Can you descriobe your restriction(s) concerning "invoke the script at the command prompt"?  There may be ways around that.

  • Python Script to Generate MySQL Stored Routines

    Here is a quick Python script that reads a MySQL scheme (database) and for each table, it generates Insert, Update, Get and Delete stored routines.  The script is just a "quick-n-dirty" script, but it does take into account that the Update, Get and Delete routines need to key off the primary key (and if there's not one, there could be trouble!).  Each stored routine is output into a separate file.
    I'm attaching the script so you professional Python people can tell me where I could improve the script with respect to simplicity, readability, cleanliness, etc.
    I have NOT yet got the command line parameters added to this script, but plan to soon.
    #!/usr/bin/env python
    # spgen.py
    # Copyright 2008 Matt Runion <[email protected]>
    import sys
    import MySQLdb
    # The INSERT template
    insertTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    INSERT INTO %s (
    %s
    ) VALUES (
    %s
    END$$
    DELIMITER ;
    # The UPDATE template
    updateTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    UPDATE %s SET
    %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    # The GET template
    getTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    SELECT
    %s
    FROM %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    # The DELETE template
    deleteTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    DELETE FROM %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    def generateSPs(dbhost, dbname, dbuser, dbpasswd):
    This method reads all the tables from the database and for each of them
    generates the following stored routines:
    <TableName>_Insert
    <TableName>_Update
    <TableName>_Get
    <TableName>_Delete
    # Open the database connection
    print 'Connecting to database [%s] on host [%s]' % (dbname, dbhost)
    dbConn = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpasswd, db=dbname)
    cur = dbConn.cursor()
    # Get a list of all tables in the database
    print 'Reading tables...'
    cur.execute("SHOW TABLES FROM %s" % dbname)
    tables = cur.fetchall()
    for table in tables:
    print 'Generating stored procs for table [%s]...' % table[0]
    # Get a list of a columns in the current table
    cur.execute("SHOW COLUMNS FROM %s" % table[0])
    columns = cur.fetchall()
    insertUpdateParms = ''
    getDeleteParms = ''
    whereClause = ''
    insertList = ''
    valuesList = ''
    updateList = ''
    for column in columns:
    # Reset some variables
    print ' %s -- %s [%s, %s, %s]' % (column[0], column[1], column[2], column[3], column[4])
    # Append the columns to the input parms
    if (len(insertUpdateParms) > 0):
    insertUpdateParms += ',\n'
    insertList += ',\n'
    valuesList += ',\n'
    if (len(updateList) > 0):
    updateList += ',\n'
    insertUpdateParms += '%sIN ' % column[0]
    if ((column[1][0:3].lower() == 'var') or (column[1][0:3].lower() == 'cha')):
    insertUpdateParms += '%s' % column[1]
    elif (column[1][0:3].lower() == 'enu'):
    insertUpdateParms += 'varchar(50)'
    else:
    insertUpdateParms += (column[1].split('('))[0]
    insertList += column[0]
    valuesList += '%sIN' % column[0]
    # Generate the key parms that are used for the Get and Delete
    # stored procs, and generate the values for the WHERE clause
    # for the Update, Get and Delete stored procs
    if (column[3].lower() == 'pri'):
    if (len(getDeleteParms) > 0):
    getDeleteParms += ',\n'
    getDeleteParms += '%sIN ' % column[0]
    if (column[1][0:3].lower() == 'var'):
    getDeleteParms += '%s' % column[1]
    else:
    getDeleteParms += (column[1].split('('))[0]
    if (len(whereClause) > 0):
    whereClause += ' AND \n'
    whereClause += '%s = %sIN' % (column[0], column[0])
    else:
    updateList += '%s = %sIN' % (column[0], column[0])
    #print '---'
    #print insertUpdateParms
    #print '---'
    #print getDeleteParms
    #print '---'
    #print whereClause
    #print 'INSERT:'
    #print insertTemplate % (table[0] + '_Insert', table[0] + '_Insert', insertUpdateParms, table[0], insertList, valuesList)
    #print 'UPDATE:'
    #print updateTemplate % (table[0] + '_Update', table[0] + '_Update', insertUpdateParms, table[0], updateList, whereClause)
    #print 'GET:'
    #print getTemplate % (table[0] + '_Get', table[0] + '_Get', getDeleteParms, insertList, table[0], whereClause)
    #print 'DELETE:'
    #print deleteTemplate % (table[0] + '_Delete', table[0] + '_Delete', getDeleteParms, table[0], whereClause)
    # Write out the INSERT stored proc
    file = open('./test/' + table[0] + '_Insert', 'w')
    file.write(insertTemplate % (table[0] + '_Insert', table[0] + '_Insert', insertUpdateParms, table[0], insertList, valuesList))
    file.close()
    # Write out the UPDATE stored proc
    file = open('./test/' + table[0] + '_Update', 'w')
    file.write(updateTemplate % (table[0] + '_Update', table[0] + '_Update', insertUpdateParms, table[0], updateList, whereClause))
    file.close()
    # Write out the GET stored proc
    file = open('./test/' + table[0] + '_Get', 'w')
    file.write(getTemplate % (table[0] + '_Get', table[0] + '_Get', getDeleteParms, insertList, table[0], whereClause))
    file.close()
    # Write out the DELETE stored proc
    file = open('./test/' + table[0] + '_Delete', 'w')
    file.write(deleteTemplate % (table[0] + '_Delete', table[0] + '_Delete', getDeleteParms, table[0], whereClause))
    file.close()
    return 0
    if __name__ == '__main__':
    generateSPs('<SERVER>', '<DATABASE>', '<USER>', '<PASSWD>')

    I found and fixed a bug with some misplaced parenthesis that forced the path to be made all lower-case.  This was a bad thing if the path had some upper case letters in it!
    #!/usr/bin/env python
    # spgen.py
    # Copyright 2008 Matt Runion <[email protected]>
    # This program is free software; you can redistribute it and/or modify
    # it under the terms of the GNU General Public License as published by
    # the Free Software Foundation; either version 2 of the License, or
    # (at your option) any later version.
    # This program is distributed in the hope that it will be useful,
    # but WITHOUT ANY WARRANTY; without even the implied warranty of
    # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    # GNU General Public License for more details.
    # You should have received a copy of the GNU General Public License
    # along with this program; if not, write to the Free Software
    # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
    # MA 02110-1301, USA.
    import sys
    import getopt
    import os
    import MySQLdb
    # The INSERT template
    insertTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    INSERT INTO %s (
    %s
    ) VALUES (
    %s
    END$$
    DELIMITER ;
    # The UPDATE template
    updateTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    UPDATE %s SET
    %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    # The GET template
    getTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    SELECT
    %s
    FROM %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    # The DELETE template
    deleteTemplate = """
    DELIMITER $$
    DROP PROCEDURE IF EXISTS `%s`$$
    CREATE PROCEDURE `%s` (%s)
    BEGIN
    DELETE FROM %s
    WHERE
    %s;
    END$$
    DELIMITER ;
    def generateSPs(dbhost, dbname, dbuser, dbpasswd, outPath):
    This method reads all the tables from the database and for each of them
    generates the following stored routines:
    <TableName>_Insert
    <TableName>_Update
    <TableName>_Get
    <TableName>_Delete
    # Open the database connection
    print 'Connecting to database [%s] on host [%s]' % (dbname, dbhost)
    dbConn = MySQLdb.connect(host=dbhost, user=dbuser, passwd=dbpasswd, db=dbname)
    cur = dbConn.cursor()
    # Get a list of all tables in the database
    print 'Reading tables...'
    cur.execute("SHOW TABLES FROM %s" % dbname)
    tables = cur.fetchall()
    for table in tables:
    print 'Generating stored procs for table [%s]...' % table[0]
    # Get a list of a columns in the current table
    cur.execute("SHOW COLUMNS FROM %s" % table[0])
    columns = cur.fetchall()
    insertUpdateParms = ''
    getDeleteParms = ''
    whereClause = ''
    insertList = ''
    valuesList = ''
    updateList = ''
    for column in columns:
    # Reset some variables
    print ' %s -- %s [%s, %s, %s]' % (column[0], column[1], column[2], column[3], column[4])
    # Append the columns to the input parms
    if (len(insertUpdateParms) > 0):
    insertUpdateParms += ',\n'
    insertList += ',\n'
    valuesList += ',\n'
    if (len(updateList) > 0):
    updateList += ',\n'
    insertUpdateParms += '%sIN ' % column[0]
    if ((column[1][0:3].lower() == 'var') or (column[1][0:3].lower() == 'cha')):
    insertUpdateParms += '%s' % column[1]
    elif (column[1][0:3].lower() == 'enu'):
    insertUpdateParms += 'varchar(50)'
    else:
    insertUpdateParms += (column[1].split('('))[0]
    insertList += column[0]
    valuesList += '%sIN' % column[0]
    # Generate the key parms that are used for the Get and Delete
    # stored procs, and generate the values for the WHERE clause
    # for the Update, Get and Delete stored procs
    if (column[3].lower() == 'pri'):
    if (len(getDeleteParms) > 0):
    getDeleteParms += ',\n'
    getDeleteParms += '%sIN ' % column[0]
    if (column[1][0:3].lower() == 'var'):
    getDeleteParms += '%s' % column[1]
    else:
    getDeleteParms += (column[1].split('('))[0]
    if (len(whereClause) > 0):
    whereClause += ' AND \n'
    whereClause += '%s = %sIN' % (column[0], column[0])
    else:
    updateList += '%s = %sIN' % (column[0], column[0])
    # Write out the INSERT stored proc
    file = open(os.path.join(outPath,(table[0] + '_Insert.sql').lower()), 'w')
    file.write(insertTemplate % (table[0] + '_Insert', table[0] + '_Insert', insertUpdateParms, table[0], insertList, valuesList))
    file.close()
    # Write out the UPDATE stored proc
    file = open(os.path.join(outPath,(table[0] + '_Update.sql').lower()), 'w')
    file.write(updateTemplate % (table[0] + '_Update', table[0] + '_Update', insertUpdateParms, table[0], updateList, whereClause))
    file.close()
    # Write out the GET stored proc
    file = open(os.path.join(outPath,(table[0] + '_Get.sql').lower()), 'w')
    file.write(getTemplate % (table[0] + '_Get', table[0] + '_Get', getDeleteParms, insertList, table[0], whereClause))
    file.close()
    # Write out the DELETE stored proc
    file = open(os.path.join(outPath,(table[0] + '_Delete.sql').lower()), 'w')
    file.write(deleteTemplate % (table[0] + '_Delete', table[0] + '_Delete', getDeleteParms, table[0], whereClause))
    file.close()
    return 0
    def main(argv):
    SPGen reads all the tables from the given database and for each of
    those tables generates the following stored routines:
    <TableName>_Insert
    <TableName>_Update
    <TableName>_Get
    <TableName>_Delete
    Command line arguments are:
    -?, --help: Help
    -o, --outputpath: File output path
    -h, --host: Database host/server
    -d, --database: Database name
    -u, --user: Database user
    -p, --password Database password
    # Set defaults...
    outputPath = os.getcwd()
    host = 'localhost'
    database = ''
    user = ''
    password = ''
    # See what command line options we have
    try:
    opts, args = getopt.getopt(argv[1:], '?o:h:d:u:p:', ['help', 'outputpath=', 'host=', 'database=', 'user=', 'password='])
    except getopt.GetoptError:
    print main.__doc__
    sys.exit(2)
    for opt, arg in opts:
    if opt in ['-?', '--help']:
    print main.__doc__
    sys.exit()
    elif opt in ['-o', '--outputpath']:
    outputPath = arg
    elif opt in ['-h', '--host']:
    host = arg
    elif opt in ['-d', '--database']:
    database = arg
    elif opt in ['-u', '--user']:
    user = arg
    elif opt in ['-p', '--password']:
    password = arg
    generateSPs(dbhost=host, dbname=database, dbuser=user, dbpasswd=password, outPath=outputPath)
    if __name__ == '__main__':
    main(sys.argv)
    Last edited by mrunion (2008-11-20 19:33:37)

  • Python script named in output of ps -u user

    Does anyone here know how I can have a Python script report it's name in the output of "ps -u user", instead of just showing up as "Python"?
    Reason I'm asking is that I just found this nifty little menu program called pytmenu on the Ubuntu forums, and I want it to start in the center of my screen. Problem is, I'm using Evilwm, so I can do it either with switches passed to Evilwm or Devil's Pie, but I need to know the programs name to do it. Passing "Python" as the name will probably not get me the results I want.

    oh. also.. if you want to change the process name from within python..
    http://davyd.livejournal.com/166352.html

Maybe you are looking for

  • Spry menu hover: How to get rid of white box with "false"?

    Hi-- I'm encountering an IE issue with a Spry vertical menu bar. When the user hovers over the submenu, white frames appear behind the submenu with the word "false" in them. Of course this doesn't happen in Safari or Firefox. I was able to fix other

  • ICal: cannot turn off holiday notifications!

    hi Folks, my iCal keeps giving me these annoying holiday notifications, for every holiday in Canada, even for provinces I'm not located in.  This not only clutters up the calendars, but I manually have to close all these popups when they appear on my

  • Apple ID Support?

    Hi, I am trying to set up an apple id on my sons new ipod touch, it says on the apple site that it has sent (and resent!) the verification email to the email address but nothing ever appears in the inbox. I definitely have the correct email address.

  • Qosmio F20-141 - Cannot start Win XP PRO SP2 installation.

    Cannot start Win XP PRO SP2 installation. After choose "start from CD" i can see for a little time only starting message ~"Starting Wisdows XP installation" (little white letters on top of black screen) After this computer hungs in black screen. QOSM

  • Manage Printer Specific Settings

    OSX Tiger Server: Is there a way to enforce certaing printer specific settings on the server queue? For instance force every user printer preferences to defualt to dual sided printing for a specific device or default to Black and White printing on BW