How can commands be run from D? - command

So, I'm coming from Java and I'd like to use a small D script to start a server with a bunch of parameters. So, instead of typing
java -someargs... -jar really-long-jar-name.jar
I would like to just click on the executable.
Is there any equivalent to Runtime#exec in D?

You can use std.process.executeShell or std.process.execute to achieve this:
import std.process : executeShell;
auto res = executeShell("java -jar my_program.jar");
if(res.status != 0)
{
...
}

Related

Scala / Special character handling / How to turn m�dchen to mädchen?

I've got a Scala Akka App where I execute python scripts inside Futures with ProcessBuilder.
Unfortunately are special character not displayed correct, so do I get instead of mädchen-> m�dchen
(äöü -> �)
If I execute the python script via command line do I get the right output of "mädchen", so I assume it has nothing to do with the python script instead somehow related to my Scala input read.
Python Spider:
print("mädchen")
Scala:
val proc = Process("scrapy runspider spider.py")
var output : String = ""
val exitValue = proc ! ProcessLogger (
(out) => if( out.trim.length > 0 )
output += out.trim,
(err) =>
System.err.printf("e:%s\n",err)
)
println(exitValue) // 0 -> succ.
println(output) // m�dchen -> should be mädchen
I already tried many thinks and also read that Strings are by default UTF-8 so I am not sure why I get those question marks.
Also did I tried with no success:
var byteBuffer : ByteBuffer = StandardCharsets.UTF_8.encode(output.toString())
val str = new String(output.toString().getBytes(), "UTF-8")
Update:
It seems to be a windows related issue, following instruction will solve this problem: Using UTF-8 Encoding (CHCP 65001) in Command Prompt / Windows Powershell (Windows 10)

How to run e file one by one? Not in parallel test

I am new to specman, I am now writing a testbench which i want to give many specific test cases to debug a calculator.
For example,
I have two files, the first one called "test1" and the second called "test2".
Here is my code for "test1":
extend instruction_s {
keep cmd_in_1 == ADD;
keep din1_1 < 10;
keep din2_1 < 10;
};
extend driver_u {
keep instructions_to_drive.size() == 10;
};
And here is my code for "test2":
extend instruction_s {
keep cmd_in_1 == SUB;
keep din1_1 < 10;
keep din2_1 < 10;
};
extend driver_u {
keep instructions_to_drive.size() == 10;
};
However, when I tried to test my code, specman shows error, it seems I can't do this like that.
Is there any possible way that I can let specman execute "test1" file first and then run "test2" file?
Or if there is some other way that I can achieve my goal?
Thanks for your helping.
Do you really want to have one test that executes 10 ADD instructions, and run another test that executes 10 SUB instructions?
If so, the common way to do so is to compile your testbench, and run multiple times - each time loading another test file.
For a start, try this:
xrun my_device.v my_testbench.e test1.e
xrun my_device.v my_testbench.e test2.e

Shell like application using sbt console

I would like to deploy some scala code, to be used very similar to sbt console
(command line interface, history, etc)
and would like to
customize it
and made it simple to deploy.
Can sbt console be used with these changes:
Removed startup info messages
Removed scala welcome message
Customized command prompt instead of "scala>" to be "myApp>"
No access to local nor global ivy/maven repositories (all jars
available, including sbt jars and dependencies)
Anybody passed this path ?
I have tried
Using sbt to build command line application
but with no much progress so far
(I guessed it was intented to very similar situation)
Are there ready made plugin available ?
Any other tool related or unrelated to sbt ?
Thank you
Actully, no need for sbt. To have it tweaked, scala code should be changed.
For the sbt "Customized command prompt" part, you have a good example with "sbt: Customize the Shell prompt in sbt" from Patrick Bailey (patmandenver).
create the ~/.sbt/0.13/global.sbt file:
vi ~/.sbt/0.13/global.sbt
And place the following in it.
shellPrompt := { state =>
def textColor(color: Int) = { s"\033[38;5;${color}m" }
def backgroundColor(color:Int) = { s"\033[48;5;${color}m" }
def reset = { s"\033[0m" }
def formatText(str: String)(txtColor: Int, backColor: Int) = {
s"${textColor(txtColor)}${backgroundColor(backColor)}${str}${reset}"
}
val red = 1
val green = 2
val yellow = 11
val white = 15
val black = 16
val orange = 166
formatText(s"[${name.value}]")(white, orange) +
"\n " +
formatText("\u276f")(green, black) +
formatText("\u276f")(yellow, black) +
formatText("\u276f ")(red, black)
}
Run reload in sbt and….
That can be amended/enhanced/completed to add other information you would need in your case.

Launch specific external process in Scala

I've been struggling to launch a specific external process in Scala. It works for most programs, but when I try
Array("gnome-terminal", "--working-directory",
"/mydir", "-x", "bash", "-c", "tmux attach")
it fails. I tried the same using Python's subprocess.Popen and it worked perfectly. Any suggestion?
My code is:
object Test {
def main(args: Array[String]):Unit = {
val source = Source.fromFile("file.txt")
val lines = source.getLines
lines.toList.map(raw => {
val programAndOptions = raw.split('$')
// here I get the Array mentioned above
Process(programAndOptions) run
})
source.close
}
}
Update
My file.txt is something like this:
evince$/path/to/my/pdf
evince$/path/to/other/pdf
nautilus$/path/to/my/working/directory
gnome-terminal$--working-directory$/mydir$-x$bash$-c$tmux attach
Update2
I ran the same code again to test and try some other things and it worked 'as is'.
'Run' is non blocking so it execute the program and continue with the code, which is this case is source.close and exit. Exiting the jvm probably kill the app.
Try using the '!' function instead of 'run' or do something like:
val p = Process(programAndOptions) run
p.exitValue

Jython Build has no Output

Hey, I've been playing around with Jython a bit and I wrote the following test program:
from javax.swing import *
from java.awt import *
from java.awt.event import ActionListener
class JythonTest(JFrame):
_windowTitle = ""
def __init__(self):
self.initVars()
self.initLookAndFeel()
self.initComponents()
self.initGui()
def initVars(self):
self._windowTitle = "Jython Test"
JFrame.__init__(self, self._windowTitle)
def initLookAndFeel(self):
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
def initComponents(self):
label = JLabel("Hello World!", JLabel.CENTER)
label.setFont(Font("Arial", Font.BOLD, 30))
tabs = JTabbedPane()
tabs.addTab("Test", label)
tabs.addTab("Calculator", self.CalculatorPane())
self.add(tabs)
def initGui(self):
self.setSize(400,200)
self.setDefaultCloseOperation(self.EXIT_ON_CLOSE)
self.setVisible(1)
class CalculatorPane(JPanel, ActionListener):
_txt1 = 0
_txt2 = 0
_box = 0
def __init__(self):
self.initVars()
self.initComponents()
def initVars(self):
pass
def initComponents(self):
self._txt1 = JTextField(5)
self._box = JComboBox(["+", "-", "*", "/"])
self._txt2 = JTextField(5)
btn = JButton("Go")
btn.addActionListener(self)
self.add(self._txt1)
self.add(self._box)
self.add(self._txt2)
self.add(btn)
def actionPerformed(self, ev):
val1 = self._txt1.getText()
val2 = self._txt2.getText()
operation = self._box.getSelectedItem()
val1 = int(val1)
val2 = int(val2)
if operation == "+":
answer = val1+val2
elif operation == "-":
answer = val1-val2
elif operation == "*":
answer = val1*val2
elif operation == "/":
answer = val1/val2
JOptionPane.showMessageDialog(self, "The answer is: " + str(answer))
if __name__ == "__main__":
win = JythonTest()
Here's my system info:
Operating System: Ubuntun 10.10
Netbeans Version: 6.9
My problem is that I can't compile the above code. It runs just fine when I click the run button, however, when I hit build or clean & build then I don't get any results. The build process runs in the bottom right corner for about half a second and then finishes. The output box opens up but it's entirely empty, even after the process ends. When I look at my project folder, nothing changes. Only two folders exist, nbproject and src. There probably should be a dist folder with a jar inside of it. Here's what's in the file structure:
user#computer: ~/NetBeansProjects/pythontest$ ls
nbproject src
user#computer: ~/NetBeansProjects/pythontest$ ls nbproject
private project.properties project.xml
user#computer: ~/NetBeansProjects/pythontest$ ls nbproject/private
private.xml
user#computer: ~/NetBeansProjects/pythontest$ ls src
pythontest.py setup.py
All I did to set up was install netbeans from the debian package (quite a while ago) and set up python/jython through the NetBeans python plugin. Any idea what's wrong?
The short answer is that it doesn't really work like that; I'm not aware of any IDE or tool support for packaging jython programs.
Usually what I do is just make a shell script that says:
java -cp "the/classpath/;" org.python.util.jython myscript.py
I've found that is the most foolproof way to run a jython program, and has saved me many headaches from not-working .jar files during development.
That said, there are methods of packaging jython programs in standalone .jar files, if that's what you want.
The best resource that I've found is the Distributing Jython Scripts page in the Jython FAQ, which describes a few different techniques for distributing jython scripts.
I usually only use the methods described there when "publishing" a program.