I am trying to pass in a value i got in a views.py file in Django into another python script i wrote, but i have no idea how to do so. Here is my code from views.py file:
def get_alarm_settings(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
alarm = Alarm.objects.all()[0].alarm_setting
response = HttpResponse(alarm, content_type='text/plain')
response_a = execfile('alarm_file.py')
return response_a
I am trying to pass response into alarm_file.py, does anyone know how to do that?
As per comments under the question, make function in alarm_file.py and import it. To make python alarm_file.py
call do the same, use if __name__ == '__main__':
an alarm_file.py. It will contain logic to run when called python alarm_file.py
. Additionally, you can use sys.argv
to get argument, passed in command line. For example:
alarm_file.py:
import sys
def do_something(val):
# do something
print val
# return something
return val
if __name__ == '__main__':
try:
arg = sys.argv[1]
except IndexError:
arg = None
return_val = do_something(arg)
This will ensure that you can run simply: python alarm_file.py some_argument
In your view just import function from alarm_file and use it:
from alarm_file import do_something
...
response = HttpResponse(alarm, content_type='text/plain')
response_a = do_something(response)
return response_a
您可以使用流程响应中间件来处理从view方法返回的响应,有关更多详细信息,请参见https://docs.djangoproject.com/en/dev/topics/http/middleware/#process-response
You cannot pass arguments using execfile(), if you want to call another instance of the interpreter and run the script, you should probably use subprocess.popen ( suprocess docs )
Something like this: subprocess.Popen(['alarm_file.py', 'arg1', ...], ..., shell=True)
I would suggest you to use Popen method of Subprocess module.
For Example:
process = Subprocess.Popen(['python','alarm_file.py','arg1','arg2'], stdout=PIPE, stderr=STDOUT)
output = process.stdout.read()
exitstatus = process.poll()
In this example, stderr and stdout of the script is saved in variable ' output ', And exit code of the script is saved in variable ' exitstatus '.
You can refer my blog for detailed explanation >>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.