简体   繁体   English

如何在django视图中运行命令行python脚本?

[英]How to run command line python script in django view?

I have a .py file that a php file runs like this: 我有一个.py文件,php文件运行如下:

$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. 我想运行xxx.py在我的Django视图和输出ASIGN给一个变量。 The xxx.py file has a def main(url) function and if __name__ == '__main__': at the bottom. xxx.py文件有一个def main(url)函数, if __name__ == '__main__':在底部。 Is there a way I can edit the xxx.py file and call the def main function from my view? 有没有办法可以编辑xxx.py文件并从我的视图中调用def main函数?

Currently it doesn't run like it runs on command line when called directly from the view. 目前,它不像在视图中直接调用时那样在命令行上运行。

Thanks for your response. 感谢您的答复。

Is there a way I can edit the xxx.py file and call the def main function from my view? 有没有办法可以编辑xxx.py文件并从我的视图中调用def main函数?

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. 修改main函数,使其以字符串形式返回结果,而不是将其打印到stdout ,这就是它目前正在做的事情。

Then, from inside your view, you can do something like: 然后,从您的视图中,您可以执行以下操作:

import xxx
results = xxx.main('foo')
# Do something with results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM