PowerShell [System.IO.StreamWriter] to write to console (Write-Host)? - ios

I know that I write into a file by using:
$stream = [System.IO.StreamWriter] "file.txt"
As I need to use a stream I really would know if I can replace "file.txt" by something so that what ever is written to the stream is printed to the console (write-host) or to write-progress?
Thanks in advance

I would look at writing a function that will perform both of those operations. This is pretty generic but would take the input that you want from the pipeline and then write to the stream as well as writing the output to the console.
# Generic function name modeled after Tee-Object, which outputs to console and file
Function Tee-Object1 {
Param (
[parameter(ValueFromPipeline=$True)]
$InputObject
)
Process {
# Write to stream
[void]$Script:Stream.Write($_)
# Write to console
$_
}
}
$Script:stream = [System.IO.StreamWriter] "file.txt"
# Whatever your data is will be piped into the function
$data | Tee-Object1

You should be able to use [Console]::Out now to get a reference to the current stdout stream
https://learn.microsoft.com/en-us/dotnet/api/system.console.out?view=netcore-3.1#System_Console_Out

Related

OPA unit-test failing, How to output response variable?

Newbie to OPA, I am writing OPA unit test case.
test_valid_type {
response = evaluate with
input as valid_type
response == "approved"
}
it's failing response == "approved". I want to see the output of response variable, how do i output it?
Try the trace method provided by OPA for debugging.
https://www.openpolicyagent.org/docs/latest/policy-reference/#debugging
This will let you print the output.
In your example you can add trace(response) which will print the response output.
After reading many documention finally found it.
trace(variable)
prints the content of the variable.
[Ref][1]

Script returns a value in the stadout but not able to get value in return parameter

I am using the callexec function to call a python script. The python script returns a value in the stadout but I am not able to get the value in the return parameter. Is there a way to pass the value to the results variable?
The is the CANape script that I am using:
double err;
char result[];
err = CallExecutable("C:\\Program Files (x86)\\Python38-32\\python.exe", "C:\\Users\\XXXX\\Desktop\\Read_Current.py 1", 1, result);
print("%s", result);
Thanks in advance
The result buffer provided to CallExecutable will return the result of the exit code from the python program. The following python code if called will return 123 and that is what the value of result will be in your code above.
import sys
sys.exit(123)
If you are looking to pass data back from the python script I've done this using the function DLL mechanism (there is some demo code included with CANape for this). It involves a little C++ wrapper to interface with python or other languages.

How to get the output of python script executed from a ruby method

I am trying to run a python script from ruby method. I am running this method as a rake task within a Rails app. I am using the solution mentioned here:
def create
path = File.expand_path('../../../../GetOrders', __FILE__)
output = `"python2 " + path + "/parse.py"`
print output
str = JSON.parse(output)
print str
end
EDIT: This works:
output = `python2 #{path}/parse.py`
EDIT2:
Using the python script i am trying to pass a list of dictionaries to the ruby function. The python script looks something like:
import xml.etree.ElementTree as ET
import json
def parse():
tree = ET.parse('response.xml')
root = tree.getroot()
namespaces = {'resp': 'urn:ebay:apis:eBLBaseComponents'}
order_array = root.find("resp:OrderArray", namespaces=namespaces)
detailsList = []
for condition:
details["key1"] = value1
details["key2"] = value2
detailsList.append(details)
output = json.dumps(detailsList)
return output
print parse()
Could someone explain what i am doing wrong and how can I fix this. Thanks
When you do this:
output = `python2 #{path}/parse.py`
output will be assigned the standard output of the python script, but that script isn't writing anything to standard output; the json data that's the return value of the parse() call is simply discarded. You seem to be expecting the execution of the script to have a "return value" that's the return value of the script's last expression, but that's not how processes work.
You probably want to replace the parse() call at the end of the script with print parse().
You are calling this exact line on the shell:
"python2 -path- /parse.py"
which the shell interprets as a single command: python2 (with a space at the end).
Try using string interpolation, which works with the backtick operator:
output = `python2 #{path}/parse.py`
Imagine typing this exact string:
"python2 " + path + "/parse.py"
into your shell (e.g. bash). It would look for a program named "python2 " and give it four arguments
+
path
+
/parse.y
You can't put arbitrary Ruby code inside a backtick string the same way you can't put arbitrary code in normals strings. You must use string interpolation.

How to change output of ant <input> task?

Output of task by default look like that:
target name:
[input] some message:
your input
[next task]
I'd like to see something like this:
target name:
[input] some message: your input
[next task]
How can I make, that task does not put cursor to the new line after message?
It can be done, but it is a little bit involved. There is no option on the input task itself for easily doing what you want.
However, in Ant 1.7 or greater, you can control the output (and input) of the input task by providing an input handler. Ant comes shipped with a few input handlers, for example one for secure input that does not echo what you type to the screen. You can, if you want, write your own input handler, and in that way gain full control of what input and output looks like.
To write an input handler you must write a class that implements the InputHandler interface. I recommend you download the Ant source code and take a look at the DefaultInputHandler and create your own version of that, modifying it to suit your needs. In the source for Ant v1.8.3, the prompt and input is implemented like this:
r = new BufferedReader(new InputStreamReader(getInputStream()));
do {
System.err.println(prompt);
System.err.flush();
try {
String input = r.readLine();
request.setInput(input);
} catch (IOException e) {
throw new BuildException("Failed to read input from"
+ " Console.", e);
}
} while (!request.isInputValid());
I haven't tried it, but changing the println to a print seems like a good idea.
When done, you can point Ant's input task to your compiled input handler using the classname and (for instance) classpath parameters.

SharpSSh: RunCommand in SshExec is always returning an empty string

When Using SharpSSh and the SshExec class, I can't get the RunCommand to work, it always returns an empty string. When I debug the SharpSsh library it returns -1 when it tries to read the command from a stream. It works when I use the sftp class in the same library, but that class doesn't support all the ftp commands I need.
Here is a standard example, I can't get this to produce a correct result either
SshConnectionInfo input = Util.GetInput();
SshExec exec = new SshExec(input.Host, input.User);
if(input.Pass != null) exec.Password = input.Pass;
if(input.IdentityFile != null) exec.AddIdentityFile( input.IdentityFile );
Console.Write("Connecting...");
exec.Connect();
Console.WriteLine("OK");
while(true)
{
Console.Write("Enter a command to execute ['Enter' to cancel]: ");
string command = Console.ReadLine();
if(command=="")break;
string output = exec.RunCommand(command);
Console.WriteLine(output);
}
Console.Write("Disconnecting...");
exec.Close();
Console.WriteLine("OK");
Any ideas on how I can get the RunCommand function to run some commands?
Thanks for any help :)
To get the standard output and error streams from .RunCommand,
I'll repeat the answer I posted to: SharpSSH - SSHExec, run command, and wait 5 seconds for data!
You may want to try the following overload:
SshExec exec = new SshExec("192.168.0.1", "admin", "haha");
exec.Connect();
string stdOut = null;
string stdError = null;
exec.RunCommand("interface wireless scan wlan1 duration=5", ref stdOut, ref stdError);
Console.WriteLine(stdOut);
exec.Close();
If their API does what the name implies, it should put the standard output of your command in stdOut and the standard error in stdError.
For more information about standard streams, check this out: http://en.wikipedia.org/wiki/Standard_streams

Resources