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
Similar Messages
-
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() -
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, JarnoYou 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 -
Communicat​ing with Keithley 2602A using python script
Hi everyone,
I want to enable communication between my PC and Keithley 2602A SourceMeter Instrument so that I can send commands to the SMI without using Test Script Builder (TSB) - a scripting/remote controlling program that enables communication between itself and the host computer.
The reason why I want to do this is because I want to program in Python to carry out a series of tasks involving other hardwares and adjusting the voltage on the SMI at the same time. I can't use TSB to do this because TSB is solely for controlling the SMI and not other hardwares. I need to use Python scripts to consolidate all the hardware control. So far, communicating with other hardwares from my PC using Python scripts is not a problem because I have readily available libraries for them.
I have found PyVisa which I thought could solve the communication problem. So I installed PyVisa and wrote the following code to test the communication.
import visa
keithley = visa.instrument("COM1") #SMI connected to COM1
keithley.write("smua.source.output = smua.OUTPUT_ON") #send this command to SMI
However, the communication was not successful as I got the error message as shown below:
C:\Documents and Settings\cho\Desktop\Python Ex>keithley_test.py
Traceback (most recent call last):
File "C:\Documents and Settings\cho\Desktop\Python Ex\keithley_test.py", line 2, in <module>
keithley = visa.instrument("COM1")
File "C:\Python26\Lib\site-packages\pyvisa\visa.py", line 292, in instrument
return SerialInstrument(resource_name, **keyw)
File "C:\Python26\Lib\site-packages\pyvisa\visa.py", line 680, in __init__
"delay", "send_end", "values_format")))
File "C:\Python26\Lib\site-packages\pyvisa\visa.py", line 358, in __init__
"lock")))
File "C:\Python26\Lib\site-packages\pyvisa\visa.py", line 132, in __init__
keyw.get("lock", VI_NO_LOCK))
File "C:\Python26\Lib\site-packages\pyvisa\vpp43.py", line 753, in open
byref(vi))
File "C:\Python26\Lib\site-packages\pyvisa\vpp43.py", line 398,
in check_status raise visa_exceptions.VisaIOError, status
pyvisa.visa_exceptions.VisaIOError: VI_ERROR_RSRC_BUSY: The resource is valid, but VISA cannot currently access it.
Can anyone tell me what went wrong? How can I control the Keithley 2602A using a Python script run from my PC?Hi DavItron, this is a very old thread but it's one of the top google results when I looked up info on how to implement some Python code with PyVISA to drive the Keithley 2602A so I will post this response so that other searchers can find the info.
You can store data in named variables in the Keithely 2602A and then "print" them to the remote interface using something like the following:
import visa
ps = visa.Instrument("GPIB::Address of your instrument")
ps.write("smua.source.levelv=10")
ps.write("smua.source.output=smua.OUTPUT_ON")
ps.write("currenta, voltagea = smua.measure.iv()")
ps.write("smua.source.output=smua.OUTPUT_OFF")
current = ps.ask("print(currenta)")
voltage = ps.ask("print(voltagea)")
For what I do which is mostly setting and measuring a bias point, then holding that while I trigger a measurement on another instrument, this is fine for me. If you want to do sweeps with a lot of data points it's probably more efficient to use the buffers directly, but I haven't needed that yet.
Hope that helps somebody! -
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 -
When I run this script nothing is output to the screen or spooled to a file
When I run this script nothing is output to the screen or spooled to a file. What do I need to do to get output from this script.
SET SERVEROUTPUT ON size 100000
DECLARE
v_schema Varchar2(50);
v_statement Varchar2(500);
v_name varchar2(30);
v_id varchar2(8);
v_pwd varchar2(16);
v_acct varchar2(16);
CURSOR get_schemas IS
SELECT DISTINCT owner
FROM all_tables
WHERE table_name = 'USERID'
ORDER BY owner;
BEGIN
OPEN get_schemas;
LOOP
FETCH get_schemas INTO v_schema;
EXIT WHEN get_schemas%NOTFOUND;
v_statement := 'SELECT name,usid,passwd,acctnum INTO v_name,v_id,v_pwd,v_acct FROM '||v_schema||'.userid';
execute immediate v_statement;
DBMS_OUTPUT.PUT_LINE('Name='||v_name||' ID='||v_id||' PW='||v_pwd||' AC='||v_acct);
END LOOP;
CLOSE get_schemas;
END;
/Do I include several variables after the INTO or just
one?
How do I loop through the record and print the
individual variables?
I appreciate your assistance!He already gave you the answer above:
v_statement := 'SELECT name,usid,passwd,acctnum FROM ' || v_schema ||
'.userid';
execute immediate v_statement
INTO v_name, v_id, v_pwd, v_acct;
If this is not printing any output, it is because you don't have a table named USERID... what are you trying to do? -
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 AMthank 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 -
Anyone running ArcGIS arcpy Python scripts using Oracle 11g EM AGENT?
I have a Windows command file that successfully executes an ArcGIS arcpy Python script when run manually or via Task Scheduler . But when executed by the EM Agent, arcpy doesn't recognize the SDE connection string file as a workspace for connecting to the geodatabase. The manual execution on the server uses the same login as the EM Agent.
I have verified all the environment variables for the EM Agent are the same as those for running natively on the server. I then used arcpy to describe the file type using both execution methods.
DescribeFile.py
import os
import sys
import arcpy
desc arcpy.Describe("D:\\Test\\Compress\\database_login.sde")
print desc.dataElementType
Manual output of: python.exe DescribeFile.py >> DEWorkspace
EM Agent output of: python.exe DescribeFile.py >> DEFile
I have little experience with Python, but years of experience with the EM Agent. I have been unable to find anything related that was helpful on Oracle Support, ESRI support, or general internet searches.I am a non arcpy user but should it not be desc =
Or is it a typo?
And maybe try using / instead of \\
Eric -
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 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. -
How to run a Python Script in Terminal ?
Hello,
how can you run a Python Script in Terminal ? (OS X 10.4.5 - not OS X Server)
It´s about this Sript:
http://www.macosxhints.com/article.php?story=20060225091102170
Thanks
iMac G5 20" Mac OS X (10.4.5)While this isn't really specific at all to OS X Server (please keep your questions in the "Mac OS X Server" topic area related to OS X Server, it helps you and everyone else
Now then:
Please note the comments of "robg" (the site-"mom"/host):
"You'll want to save the script without the .txt extension, and remember to make it executable with chmod a+x site2template.sh
Save the file to your Desktop, and remove the ".txt" from the name so it's named: site2template.sh
then in the Terminal, issue:
chmod +x ~/Desktop/site2template.sh
"~" is shortcut for "the current user's (my) home directory"
From there you can simply use:
~/Desktop/site2template.sh /your/site
But, far better to:
choose a location to save the script, typically /usr/local/bin:
make the directory if you don't have one:
sudo mkdir /usr/local/bin
sudo cp ~/Desktop/site2template.sh /usr/local/bin/
then adjust the permissions:
sudo chmod 755 /usr/local/bin/site2template.sh
You may want to add /usr/local/bin to your path.
cat /etc/profile
and if you don't see it, add:
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin"
export PATH
ie:
sudo cp /etc/profile /etc/profile.bak
(back it up to play safe)
sudo pico /etc/profile
and add
:/usr/local/bin
to the path info.
Save it (ctl w)
exit (ctl x)
then type: source /etc/profile
(start learning vi or emacs eventually)
and you'll be able to run:
site2template /path\ to/your/site/to\ convert -
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) -
Pacexp - python script to list REALLY explicitly installed packages
I usually just lurk the forums-- well, except for when I'm here asking for help with some PEBKAC issues... but never mind that.
This is a small python script I just wrote today while procrastinating. I'd love some feedback on the code, personally, but I'm hoping this could be useful to someone else. I always forget the stuff I have installed when I'm looking to clean my system up and `pacman -Qe` lists a lot of packages that Arch installs itself, so this is my way of dealing with it.
I'll probably be adding some other features to this script anyway, I'm gonna try to keep this post updated whenever I do so.
pacexp
A quick and dirty script to intersect the output of `pacman -Qe` with manually installed packages from /var/log/pacman.log
https://gist.github.com/spaceporn/d4ec6391a4684efb933c
If anyone has any suggestions to improve the code (even a better regexp counts), feel free to write them down here or on the gist page!karol wrote:
I use
expac "%n %N" $(comm -23 <(pacman -Qq|sort) <(pacman -Qqg base base-devel|sort)) | awk '$2 == ""' | less;
to list packages that aren't required by any other package and are not part of base or base-devel. All of them have been explicitly installed.
That's pretty cool! I'll probably save it as an alias if I ever have problems with my script -
On my MacPro with10.7.3. while running a Python script in terminal, after a while, in several hours actually, I see a system message for the Terminal app: "There is no more application memory available on your startup disk". Both RAM and VM appear to be fine at this point, i.e. Python uses only 10G of 16G RAM and VM =238G with ~1TB free. Log reads: " macx-swapon FAILED - 12" multiple times. Furthermore, other terminal windows can be opened and commands run there. It only happens with larger inputs (text files), but with inputs that are about half the size everything runs smoothly. So the issue must be the memory indeed, but where to look for the problem/fix?
http://liulab.dfci.harvard.edu/MACS/README.html
Have you tried with the --diag flag for diagnostics? Or changing verbose to 3 to show debug messages? Clearly one of three things is happening;
1. You ARE running out of disk space, but once it errors out the space is reclaimed if the output file is deleted on error. When it fails, does your output have the content generated up to the point of termination?
2. The application (Terminal) is allocated memory that you are exceeding
3. The task within Terminal is allocated memory that you are exceeding
I don't know anything about what this does but is there a way to maybe run a smaller test run of it? Something that takes 10 minutes? Just to see if it works.
Maybe you are looking for
-
Downloads disappear-or never make it despite looking like they have.
Some time ago and in an apparent "instant", Firefox stopped saving/getting/accepting/etc downloads from the www. It isn't sporadic, site-size based...the problem is 100% consistent. Everything appears to happen as it should. Prompts, help windows, ev
-
I have a 2008 black MacBook and acess UK tv through a puchased proxy. I want to purchase a Sony Bravia internet connected tv and stream the site through a tv - Sony tell me this won't work - that a latest model tv cannot capture content and sites fro
-
Hi. I want to send and email from XI to an address that comes in the payload. This payload has also information that has to be sent as an attachment in the email. If i use Michal's solution os 'mail package', i can't add the attachment of the info be
-
Zip Code Locator / Store Locator
Guys, I want to write a simple store-locator functionality in my website (Using a Mysql db with JSP-java etc.,) I am not sure of the tools I need and how to approach the problem (once I get a Map of all the zip codes)... Please throw in some ideas th
-
Hi I confuse on how to transform set difference query into java code to work in java program. how do you write a sql query in java that perform set difference. R - S R Except S (in oracle) I want to get all the elements in Set R that are not availabl