How to make a system call and read the stdout, in D? - d

I thought to try using D for some system administration scripts which require high performance (for comparing performance with python/perl etc).
I can't find an example in the tutorials I looked through so far (dsource.org etc.) on how to make a system call (i.e. calling another software) and receiving it's output from stdout, though?
If I missed it, could someone point me to the right docs/tutorial, or provide with the answer right away?

Well, then I of course found it: http://www.digitalmars.com/d/2.0/phobos/std_process.html#shell (Version using the Tango library here: http://www.dsource.org/projects/tango/wiki/TutExec).
The former version is the one that works with D 2.0 (thereby the current dmd compiler that comes with ubuntu).
I got this tiny example to work now, compiled with dmd:
import std.stdio;
import std.process;
void main() {
string output = shell("ls -l");
write(output);
}

std.process has been updated since... the new function is spawnShell
import std.stdio;
import std.process;
void main(){
auto pid = spawnShell("ls -l");
write(pid);
}

Related

How can I make SourceInsight understand smart pointers?

If my code uses smart pointers, navigation and completion don't work with SourceInsight. For example with this simple example code:
class test {
public:
void fun(){}
};
int main() {
boost::scoped_ptr<test> a;
a->fun();
return 0;
}
When I click fun() in main , SourceInsight tells me "symbol not found".
Is there something I should do to fix that, or does SourceInsight have limitations?
So I've given this a try. Downloaded, virus-scanned, signed up for free trial, installed wine, run!
Now, I can make SourceInsight import the symbols from the Boost directories:
I then enter the path to my Boost directory: Z:\home\sehe\custom\boost\
Processing takes a minute or two:
Seems ok:
Now if you import these symbols in your project:
You will find you can navigate to boost::scoped_ptr<> just fine (I double-clicked on the a in the declaration of a):
But it will not find references to fun:
Finds only the declaration:
Of course you can use simple string search, but that wasn't the point.
Here's the HTML export: https://s3.amazonaws.com/stackoverflow-sehe/f14b4ee2-9b4d-49cd-893d-cf69372dd586/HTML/test.cpp.html
Conclusion
It seems this is a limitation of SourceInsight, not due to misconfiguration.

How to get list of files opened by a process in Windows? [duplicate]

How do I get the list of open file handles by process id in C#?
I'm interested in digging down and getting the file names as well.
Looking for the programmatic equivalent of what process explorer does.
Most likely this will require interop.
Considering adding a bounty on this, the implementation is nasty complicated.
Ouch this is going to be hard to do from managed code.
There is a sample on codeproject
Most of the stuff can be done in interop, but you need a driver to get the filename cause it lives in the kernel's address space. Process Explorer embeds the driver in its resources. Getting this all hooked up from C# and supporting 64bit as well as 32, is going to be a major headache.
You can also run the command line app, Handle, by Mark Rusinovich, and parse the output.
Have a look at this file :
http://vmccontroller.codeplex.com/SourceControl/changeset/view/47386#195318
And use:
DetectOpenFiles.GetOpenFilesEnumerator(processID);
Demo:
using System;
using System.Diagnostics;
namespace OpenFiles
{
class Program
{
static void Main(string[] args)
{
using (var openFiles = VmcController.Services.DetectOpenFiles.GetOpenFilesEnumerator(Process.GetCurrentProcess().Id))
{
while (openFiles.MoveNext())
{
Console.WriteLine(openFiles.Current);
}
}
Console.WriteLine();
Console.ReadKey();
}
}
}
It has dependency over assembly System.EnterpriseServices
You can P/INVOKE into the NtQuerySystemInformation function to query for all handles and then go from there. This Google groups discussion has details.
Take a look at wj32's Process Hacker version 1, which can do what you asked, and more.
Handle is great program, and the link to codeproject is good.
#Brian
The reason for the code is that handle.exe is NOT redistributable. Nor do they release their source.
It looks as if .Net will not easily do this since it appears that an embedded device drive is requried to access the information. This cannot be done in .net without an unmanged DLL. It's relatviely deep kernel code when compared to typical .net coding. I'm surprised that WMI does not expose this.
Perhaps using command line tool:
OpenedFilesView v1.50 - View opened/locked files in your system (sharing violation issues)
http://www.nirsoft.net/utils/opened_files_view.html

How can I exit my Dart (vm) program?

(Sorry, I know that is this is mostly a repeat of John Evan's question, but the previous answer must now be outdated.)
I'd like to be able to specify an exitCode and leave the my (vm) program if a certain condition occurs (for debugging purposes only).
Note from the above I cannot import 'dart:builtin', and I can't find mention of exit() in this context in the API.
(My more detailed situation is that my work involves rather massive detailed output and as I test and debug things I have found it most convenient to just exit(); the program - clearly only appropriate during development.)
Thanks,
_g
Just use exit():
import 'dart:io';
void main() {
exit(0); // Standard out code, 0 = no errors.
}
Further searching has shown that the required support is now in the 'io' library so this is working for me:
(Nothing specific to an error code is getting printed out at the console, but that's ok.)
import('dart:io');
main() {
print("just before the exit command...");
exit(99);
print("We should not see this")
}

'PyCObject_Import("cairo", "CAPI")' C++ call yields segfault, 'import cairo' on python works

I am running OSX Lion and trying to import the python module for goocanvas, using python2.7.
I managed to successfully compile pygoocanvas-0.14.1, but when I try to import goocanvas through the python2.7 console, I get a segfault. After some debugging, I'm led to this code:
DL_EXPORT (void)
initgoocanvas (void)
{
PyObject *m, *d;
fprintf(stderr,"init<< \n");
// Pycairo_IMPORT; // XXX removed, it expands to the line below, anyways
Pycairo_CAPI = (Pycairo_CAPI_t*) PyCObject_Import("cairo", "CAPI"); // ADDED XXX
fprintf(stderr,"after import<< \n");
if (Pycairo_CAPI == NULL) {
return;
}
I discovered that the segfault happens when the C++ code of the goocanvas python module tries to import the "cairo" library through PyCObject_Import("cairo", "CAPI"). However, if I try to import the cairo module directly through the python2.7 console via import cairo, it works.
How should I proceed? I have a blind seg fault and no idea on why it happens. Remembering that I managed to compile the python goocanvas module, but it segfaults upon trying to import it on python.
What kind of console are you using? I think gtk/glib has some hooks to enable running the main loop concurrently with the REPL. This means that threads are in use, which may cause crashes if glib.threads_init() was not called.
IMHO this is broken by design, because by just importing glib or any g* module a sane Python program that uses any threads will suddenly start to segfault. Supporting threading should be the default.
In our case, the crash was caused by the logging system of glib which was forwarded to Python without holding the GIL.

C, C++ Interface with Python

I have c++ code that has grown exponential. I have a number of variables (mostly Boolean) that need to be changed for each time I run my code (different running conditions). I have done this using the argument command line inputs for the main( int argc, char* argv[]) function in the past.
Since this method has become cumbersome (I have 18 different running conditions, hence 18 different argument :-( ), I would like to move to interfacing with python (if need be Bash ). Ideally I would like to code a python script, where I set the values of data members and then run the code.
Does anyone have a any pointer/information that could help me out? Better still a simple coded example or URL I could look up.
Edit From Original Question:
Sorry I don't think I was clear with my question. I don't want to use the main( int argc, char* argv[]) feature in c++. Instead of setting the variables on the command line. Can I use python to declare and initialize the data members in my c++ code?
Thanks again mike
Use subprocess to execute your program from python.
import subprocess as sp
import shlex
def run(cmdline):
process = sp.Popen(shlex.split(cmdline), stdout=sp.PIPE, stderr=sp.PIPE)
output, err = process.communicate()
retcode = process.poll()
return retcode, output, err
run('./a.out '+arg1+' '+arg2+' '+...)
Interfacing between C/C++ and Python is heavily documented and there are several different approaches. However, if you're just setting values then it may be overkill to use Python, which is more geared toward customising large operations within your process by farming it off to the interpreter.
I would personally recommend researching an "ini" file method, either traditionally or by using XML, or even a lighter scripting language like Lua.
You can use subprocess module to launch an executable with defined command-line arguments:
import subprocess
option1 = True
option2 = Frue
# ...
optionN = True
lstopt = ['path_to_cpp_executable',
option1,
option2,
...
optionN
]
lstopt = [str(item) for item in lstopt] # because we need to pass strings
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
If you're using Python 2.7 or Python 3.2, then OrderedDict will make the code more readable:
from collections import OrderedDict
opts = OrderedDict([('option1', True),
('option2', False),
]
lstopt = (['path_to_cpp_executable'] +
list(str(item) for item in opts.values())
)
proc = subprocess.Popen(lstrun, close_fds = True)
stdoutdata, stderrdata = proc.communicate()
With the ctypes module, you can call arbitrary C libraries.
There are several ways for interfacing C and C++ code with Python:
SWIG
Boost.Python
Cython
I can only advise to have a look at swig : using director feature, it allows to fully integrate C++ and python, including cross derivation from onle language to the other