Reputation: 311
I am calling a Python program from C code using the system()
call inside a Linux machine.
Let's say the first call to the Python program reads the first 10 lines of some text file by opening the text file and reading lines 1 - 10. Now during the second call to the Python program, I want to read the next 10 lines 11-20 of the same text file that was opened during the last call to Python WITHOUT reopening the file and starting from the first line of the file. During the 3rd call to the Python program, I want to be able to read the next 10 lines 21 - 30 of the same text file WITHOUT reopening the file and starting from the beginning of the file. This goes on ...
Here is the sample code
//This is C code
...
...
int initial_line_number, final_line_number
initial_line_number = 1;
final_line_number = 10;
for(i = 1; i <= 10; i++)
{
system("python test.py initial_line_number, final_line_number"); //test.py reads a text file from initial_line number to final_line_number
initial_line_number += 10;
final_line_number +=10;
}
Can this be done? What is the most elegant way to do it?
Upvotes: 2
Views: 1836
Reputation: 6059
On a theoretical level, you might want to explore using DBus with python and c. Have a python daemon that reads your file, then from c, make a dbus call that returns x number of lines (you can specify that in a dbus header).
This way, you can keep the python file open for as long as you'd like AND you wouldn't require the system() call, which would mean your program would be more secure.
(Dbus can be run from user and system privileges, so your program does not have to be run from an admin level as long as you have permissions for it.)
Upvotes: 1
Reputation: 755064
No, you can't have the second call continue without reopening the file.
Each system()
call will run the program given as an argument and will wait for that process to die. Therefore, you get a new child each time — there is no (simple) way for the second to continue where the first left off.
(There could be complex methods, where your first process launches a Python process in the background that reads some lines and hangs around; the process you launched directly will terminate. The second call might recognize that the Python process is still hanging around and tell it to continue. But that's tricky programming — not worth the effort. And it is still true that each system()
call will run a separate process and wait for that process to die.)
Upvotes: 2
Reputation: 1052
First, your call to system()
is wrong, you have to pass a string.
Second, calling system()
is bad, and not portable. If you really want to use Python, you may use the Python C API : http://docs.python.org/2/c-api/
Upvotes: 1