Set variables to output based on regex on swig - python

I have a C++ library that I want to use in Python with SWIG. Many functions in that library have output arguments, arguments I have to set manually as OUTPUT.
The thing is these arguments are prefixed with "ao_" (argument output).
Is there a way to set every arguments prefixed with "ao_" to OUTPUT ?

Related

Extract script parameter name and value from string

I currently have a process executor which executes a script along with parameters. The script and parameters are user provided.
execute_script(script_name: str, parameters: str) -> None :
// Some logic
subprocess.Popen( ....)
The user provides both script name and parameters as a string. The execute_script(...) is a backend function which gets eventually invoked by an API exposed to the user. So, even though the parameters are executed as command-line arguments, they are not received as command-line arguments, but rather string variables.
For example:
script_name="sendEmail", parameters="--subject 'URGENT' --to 'xyz#redif.com, abc#hotmail.com'"
script_name="calculatePerformance", parameters="--revenue 193456343 --tax_per 32543 --operating_cost 3452564.256 --includeVacationDays"
script_name="generate_report", parameters"--duration 'quarterly' --dept 'Finance'"
I do not have control over the parameters being sent by yer user. We have a lot of such script and they keep increasing. So keeping a track of potential parameters per script is not feasible.
I need to ensure that only a permitted values are used for certain parameters when used in conjunction with particular scripts.
For Example:
the duration can ONLY be quarterly or monthly if script is generate_report. For any other script, any value can be provided.
I want to convert the parameters provided to the function from a string to a map, so that it is much more easier to extract and validate values for a script parameter.
Using space as delimiter to split and parse the string does not seem to be cleanest approach. Is there a more compact way to convert the parameters from string to map ?
Alternatively, any other suggestions for parsing the string?
I think you could get away with using a combination of shlex and argparse.
Use shlex.split as a way to tokenize the arguments, and then use argparse.ArgumentParser with parse_known_args to figure out the values you care about inspecting.
import argparse
import shlex
script_name = "generate_report"
parameters = "--duration 'quarterly' --dept 'Finance'"
parser_argv = [script_name, *shlex.split(parameters)]
parser = argparse.ArgumentParser()
parser.add_argument("--duration")
args, unknown = parser.parse_known_args(parser_argv)
if script_name == "generate_report":
if args.duration not in {"quarterly", "monthly"}:
raise ValueError(
f"Incorrect duration for generate_report: {args.duration}"
)
A nice thing about this design, is that if the scripts you end up invoking are already in python, you could expose the argparse setup in these tools and use them directly your method.
This would mean that you don't duplicate the parser code, allowing you to do validation as close as possible to the actual scripts inside this validator.

Sequence of arguments in Python scripting for abaqus

I have written the section assignment command in .py file with its arguments written in random order and ran it on am model in abaqusbut i am getting error.
Does the sequence of arguments for a command in Python scripting of abaqus matter ?
The SectionAssignment command may have a default order of arguments, but it's safer to use the keyword arguments syntax.
From Section 44.1.1 SectionAssignment(...) in the Abaqus v6.14 Scripting Reference Guide, the required arguments are region and sectionName, while optional arguments are thicknessAssignment, offset, offsetType, and offsetField. Your syntax should thus look like
mdb.models[modelName].parts[partName].SectionAssignment(region=regionName, sectionName=sectionString, ...)
or
mdb.models[modelName].rootAssembly.SectionAssignment(region=regionName, sectionName=sectionString, ...)
rather than passing arguments in a random order.

Is it possible to get a list of all the keyword arguments of a built-in function? [duplicate]

I'm trying to figure out the arguments of a method retrieved from a module.
I found an inspect module with a handy function, getargspec.
It works for a function that I define, but won't work for functions from an imported module.
import math, inspect
def foobar(a,b=11): pass
inspect.getargspec(foobar) # this works
inspect.getargspec(math.sin) # this doesn't
I'll get an error like this:
File "C:\...\Python 2.5\Lib\inspect.py", line 743, in getargspec
raise TypeError('arg is not a Python function')
TypeError: arg is not a Python function
Is inspect.getargspec designed only for local functions or am I doing something wrong?
It is impossible to get this kind of information for a function that is implemented in C instead of Python.
The reason for this is that there is no way to find out what arguments the method accepts except by parsing the (free-form) docstring since arguments are passed in a (somewhat) getarg-like way - i.e. it's impossible to find out what arguments it accepts without actually executing the function.
You can get the doc string for such functions/methods which nearly always contains the same type of information as getargspec. (I.e. param names, no. of params, optional ones, default values).
In your example
import math
math.sin.__doc__
Gives
"sin(x)
Return the sine of x (measured in radians)"
Unfortunately there are several different standards in operation. See What is the standard Python docstring format?
You could detect which of the standards is in use, and then grab the info that way. From the above link it looks like pyment could be helpful in doing just that.

Python default values in method declaration vs Objective-c

For all intents and purposes, an Objective-C method declaration is
simply a C function that prepends two additional parameters (see
“Messaging” in the Objective-C Runtime Programming Guide ).
Thus, the structure of an Objective-C method declaration differs from the structure of a method that uses named or keyword parameters
in a language like Python, as the following Python example
illustrates:
In this Python example, Thing and NeatMode might be omitted or might have different values when called.
def func(a, b, NeatMode=SuperNeat, Thing=DefaultThing):
pass
What's the goal of showing this example on an Objective-c related book?
This is a (poor) example of how Objective-C does not support certain features that other languages, (for example, Python) may. The text explains that while Objective-C has "named parameters" of the format
- (void)myMethodWithArgument:(NSObject *)argument andArgument:(NSObject *)another;
Those parameters do not support defaults values, which Python does.
The mention of prepending two arguments hints at how message passing in Objective-C works under the hood, which is by prepending each method with a receiver object and a selector. You don't need to know this detail in order to write code in Objective-C, especially at a beginner level, but Apple explains this process here.
def func(a, b, NeatMode=SuperNeat, Thing=DefaultThing):
pass
NeatMode, Thing are optional named parameters
in objective c they would be
- (void) func:(int)a :(int)b NeatMode:(object*)SuperNeat Thing:(object*)DefaultThing
Pleas read more about this subject
http://www.diveintopython.net/power_of_introspection/optional_arguments.html
I think the point here is to differentiate between how you are "used" to receive parameters in functions and how objective-c does. Normally:
public void accumulate(double value, double value1) {
}
And in objective-c:
-(void)accumulateDouble:(double)aDouble withAnotherDouble:(double)anotherDouble{
}

How to get contents of va_list in Python?

(I'm on Windows.)
I have a callback function in Python that is called from a DLL (I use the ctypes module). One parameter has the type va_list. Is there a way to get the contents of this? I don't get how to read the correct memory locations (here's a description).
The best would be, if there's a va_list parser for Python. Or a DLL that contains functions for getting arguments of a va_list.
Does anyone know of a solution?
I have found a solution:
You can use ctypes to call standard C functions like vsprintf which accepts a va_list parameter. (Formatted printing is want I intended to do).
This is my code to call it:
bufferString = ctypes.create_string_buffer(4096)
ctypes.cdll.msvcrt.vsprintf(bufferString, fmt.raw, ctypes.cast(ap, ctypes.c_void_p))
print ctypes.cast(bufferString, ctypes.c_char_p)
fmt.raw points to the format string, ap is the address of the va_list.

Categories