How to pass parameter while executing command in Groovy Script - groovy

command = ["C:/Users/Desktop/try.bat"]
def command1=command
def cmd = command1.execute()
cmd.waitFor()
This is my code. But I need to pass 4 arguments to try.bat. Out of these one argument is optional. How to handle it?

add more items in the array
["command", "param1", "param2"].execute()
as stated in the official docs http://groovy.codehaus.org/Executing+External+Processes+From+Groovy

Maybe you should try
def command = """C:/Users/Desktop/try.bat arg1 arg2 arg3 arg4"""
as the official docs provided suggest http://groovy.codehaus.org/Executing+External+Processes+From+Groovy

Related

exec() not working when trying to execute a string containing the command "abs.__doc__"

I am trying to execute the command abs.__ doc__ inside the exec() function but for some reason it does not work.
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
exec(proper_string)
Essentially, I am going through a series of exercises and one of them asks to provide a short description of the entered function using the __ doc__ attribute. I am trying with abs.__ doc__ but my command line comes empty. When I run python in the command line and type in abs.__ doc__ without anything else it works, but for some reason when I try to input it as a string into the exec() command I can't get any output. Any help would be greatly appreciated. (I have deliberately added spaces in this description concerning the attribute I am trying to use because I get bold type without any of the underscores showing.)
As a note, I do not think I have imported any libraries that could interfere, but these are the libraries that I have imported so far:
import sys
import datetime
from math import pi
My Python version is Python 3.10.4. My operating system is Windows 10.
abs.__doc__ is a string. You should use eval instead of exec to get the string.
Example:
function = input("Please enter the name of a function: ")
proper_string = str(function) + "." + "__doc__"
doc = eval(proper_string)
You can access it using globals():
def func():
"""Func"""
pass
mine = input("Please enter the name of a function: ")
print(globals()[mine].__doc__)
globals() return a dictionary that keeps track of all the module-level definitions. globals()[mine] is just trying to lookup for the name stored in mine; which is a function object if you assign mine to "func".
As for abs and int -- since these are builtins -- you can look it up directly using getattr(abs, "__doc__") or a more explicit: getattr(__builtins__, "abs").__doc__.
There are different ways to lookup for a python object corresponding to a given string; it's better not to use exec and eval unless really needed.

Vars.get returns a null value

def signValue = '${signature_value}.${timestamp}.${signature_value}'
def token_secret = '${APP_CLIENT_SECRET}'
log.info("token is " + signValue)
def signingKey = new javax.crypto.spec.SecretKeySpec(signValue.getBytes(),"HmacSHA256");
def mac = javax.crypto.Mac.getInstance("HmacSHA256")
mac.init(signingKey);
def hmac = mac.doFinal(token_secret.getBytes());
def result = hmac.encodeBase64().toString()
---- I want to use the above "result" variable into a Http sampler request body------
---- I tried many possible ways but I end up is getting value as null or some error--
//${__groovy(vars.get("result"))}
//vars.put("signature", vars.get(result))
I've been trying to extract the value of the variable "result" and use it in HTTP sampler results. But I ended up getting a null value or some other error. Anyone could help me to sort out this problem.
Thanks!
I don't get the point, result should be a String object, is it not what you are expecting to have?
Anyway, signValue and token_secret perhaps could be different from your expectations: using single quotes instead of double quotes you are not using GStrings (e.g. the value of token_secret will be always exactly '${APP_CLIENT_SECRET}', regardless of the value of APP_CLIENT_SECRET)
Change this line:
vars.put("signature", vars.get(result))
to this:
vars.put("signature", result)
Also don't inline JMeter variables into Groovy scripts like this:
def token_secret = '${APP_CLIENT_SECRET}'
use vars shorthand instead:
def token_secret = vars.get('APP_CLIENT_SECRET')
Because:
It conflicts with Groovy GStrings
For best performance it's recommended to cache compiled scripts (enabled by default)
and in this mode JMeter resolves only first value and caches it which means you will get the same value for every iteration
More information:
JSR223 Sampler Documentation
Apache Groovy - Why and How You Should Use It
Put vars the result:
vars.put("signature", hmac.encodeBase64().toString());
And in HTTP use ${signature}

Using cmd module: how to have sub-commands documented in `help` and integrated with autocomplete?

I'm using the cmd module and have a command called server (method do_server()) which has autocomplete out of the box (I'm on macOS). That's all fine and works like expected. But if i want to additionally also use a sub-command on the server command, things don't work out like i need it.
I would need the following:
- sub-commands should also be integrated with the help command (shouldn't be shown when entering help since they are not first level commands but should be shown when entering help server)
- sub-commands should also integrate with auto-complete
Currently i don't see a way to define sub-commands out-of-the-box. I need to implement them as arguments for a command which isn't ideal.
My question would be, how can i achieve automatic documentation of the sub-commands with help and have autocomplete so that it integrates as good as possible with cmd?
For this example, i'd like to better integrate connect as a sub-command:
from cmd import Cmd
class Tansanit(Cmd):
def do_server(self, args):
""" Show server info """
print("Some server details")
if args and args == "connect":
print("Connect to the server")
def do_quit(self, args):
""" Quit CLI """
raise SystemExit
if __name__ == '__main__':
t = Tansanit()
t.prompt = "> "
t.cmdloop()
I would prefer to have something like this:
from cmd import Cmd
class Tansanit(Cmd):
def do_server(self, args):
""" Show server info """
print("Some server details")
def do_server_connect(self, args):
""" Connect to server """
print("Connect to the server")
def do_quit(self, args):
""" Quit CLI """
raise SystemExit
if __name__ == '__main__':
t = Tansanit()
t.prompt = "> "
t.cmdloop()
Unfortunately that's not possible.
Relavant infos can be found here
Autocomplete for sub-commands
The interpreter is able to process completion for commands names, but for commands arguments you will have to help it. For the command xxx, this is done by defining a complete_xxx method. For example, if you have defined a color command, the completion method for this command could be:
_AVAILABLE_COLORS = ('blue', 'green', 'yellow', 'red', 'black')
def complete_color(self, text, line, begidx, endidx):
return [i for i in _AVAILABLE_COLORS if i.startswith(text)]
The complete_xxx method takes four arguments:
text is the string we are matching against, all returned matches must begin with it
line is is the current input line
begidx is the beginning index in the line of the text being matched
endidx is the end index in the line of the text being matched
It should return a list (possibly empty) of strings representing the possible completions. The arguments begidx and endidx are useful when completion depends on the position of the argument.
help for sub-commands
You can also define help for topics that are not related to commands:
def help_introduction(self):
print 'introduction'
print 'a good place for a tutorial'
This isn't perfect since the help will be categorized as undocumented commands but it's for an argument. But maybe still better then nothing.

How to send values into command prompt from groovy?

I tried to pass an command or value at runtime into command prompt from groovy script.
could anyone help on this ?
Put your command in an Array: then use execute () to run as in command prompt like shown below.
def command = ['ls']
command.execute()
I feel like you are looking for a method like this: Use this method.
void executejar (String jarname)
{
def command = ['java','-jar', jarname ]
println command.execute().text
}

CliBuilder not reading past first argument

I am trying to write a groovy script which uses CliBuilder to read command line arguments.
Here's my code
def cli = new CliBuilder(usage:'groovy -s "server name" -r "file name"')
cli.s('Name of the server', required: true)
cli.r('Name of the file', required: true)
def args = ['-s', 'ServerEx', '-r', 'RakeEx']
def opt = cli.parse(args)
when I run this script, it gives me error Missing required option: r
even though I have provided the argument r.
I searched for the solution but I found reading multiple arguments for the same flags,
eg. -s arg1 arg2, but not reading multiple arguments for different flags.
Any help is really appreciated. Thank you.
Well, as it turns out, I have to specify the args:1 as a property when defining flags. I just found this from this article from Javaworld: http://www.javaworld.com/article/2073443/explicitly-specifying--args--property-with-groovy-clibuilder.html
Also, as an added bonus, now I can directly access the value provided by using opt.r. It used to show boolean true/false before adding args:1

Resources