以下tests.py工作正常,并通过subprocess.call执行powershell脚本:
import subprocess
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo(10)"])
尝试从django/rest视图中执行相同的调用失败:
import subprocess
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
@api_view(['POST'])
def bar(request):
if request.method == 'POST':
subprocess.call([f"C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", ". \"./testers.ps1\";", "&Foo({request.data})"])
return Response(request.data, status=status.HTTP_201_CREATED)
else:
return Response(request.errors, status=status.HTTP_400_BAD_REQUEST)
错误:
[09/Jul/2021 08:31:52] "POST /profile-eraser/ HTTP/1.1" 201 5646
. : The term './testers.ps1' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ . "./testers.ps1"; &Foo({request.data})
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (./testers.ps1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
& : The term 'Foo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:21
+ . "./testers.ps1"; &Foo({request.data})
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (hello:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
ps脚本:
Function Foo($intIN)
{
Write-Host ($intIN + 1)
}
Write-Host "PowerShell sample says hello."
为什么我可以从tests.py运行它,但不能从django视图中运行它?对我来说,执行此操作的最佳方式是什么?
2条答案
按热度按时间lf3rwulv1#
正如@santiago squarzon指出的,我必须传递脚本文件的绝对路径。关于第二个错误,我忘记指出subprocess.call的最后一个值是一个f字符串
工作代码现在看起来是这样的:
ie3xauqp2#
这不是一个答案,而是向您展示为什么在这种情况下可能不需要函数。
如果ps脚本如下所示,则无需先点源代码加载函数,然后调用函数:
你可以这样称呼它,这可能会简化一些事情: