views:

288

answers:

1

I have a .py file that a php file runs like this:

$link = exec(dirname(__FILE__) . /xxx.py ' .excapeshellarg($url) . '2>&1', $output, $exit_code);

I want to run the xxx.py in my django view and asign the output to a variable. The xxx.py file has a def main(url) function and if __name__ == '__main__': at the bottom. Is there a way I can edit the xxx.py file and call the def main function from my view?

Currently it doesn't run like it runs on command line when called directly from the view.

Thanks for your response.

+1  A: 

Is there a way I can edit the xxx.py file and call the def main function from my view?

Yes. Modify the main function so that it returns its results as a string rather than printing it to stdout, which is what it appears to be doing at the moment.

Then, from inside your view, you can do something like:

import xxx
results = xxx.main('foo')
# Do something with results
Will McCutchen
Yes, that seems to be the right way to do it. But there is a line in the xxx.py file that does this: net = pickle.load(open(pickle_file))Django gives an error at this point in the pickle.py file saying no module named neuralnet.neuralnet.pkl file exists in the same directory as the xxx.py file. I added all folders that contain my script files to the pythonpath but no luck. I'm stumped here. :S
ninja123
+1And in your "if __name__ = '__main__':" section you can do the same and print it to have the same behavior than before.Django is written in Python, so it can import any python module and work with it from within the views..
Vincent Demeester
@ninja123: The "no module named neuralnet" error makes it sound like your `$PYTHONPATH` might need some tweaking. Inside the Django view that's calling `xxx.main`, what happens if you add the line `import neuralnet`?
Will McCutchen
@ninja123 You're probably already doing this, but have you tried adding the path to the folder directly to sys.path? ex: import sys; sys.path.append('/path/to/module/')
Eric Palakovich Carr
Oh in the .pkl file the first line is '(ineuralnet' and the neuralnet.py lies in the folder of the xxx.py Maybe i need to change that to something that can be imported?
ninja123
Ok I found it. There were lines in the .pkl file that used '(ineuralnet' to import neuralnet module. I had to change it to '(iyyy.zzz.uuu.neuralnet' and it worked. I combined all your answers to get this far. Thank!
ninja123