如何用Python将变量导入popen命令



我目前的问题是,我正在使用python和HTML创建一个应用程序,以使用HTML表单收集数据,然后将数据转换为python中的变量,然后使用子进程POPEN向Azure租户发送Azure CLI命令。当我将以下代码用于该命令时,它将返回一个错误。

Python代码

@app.route('/storageaccountcreate', methods = ['POST'])
def storageaccountcreate():
name = request.form['storageaccountname']
resourcegroup = request.form['resourcegroup']
subscription = request.form['subscription']
location = request.form['location']
sku = request.form['sku']
cmd = f"az storage account create -n {name} -g {resourcegroup} --subscription {subscription} -l {location} --sku {sku}"
#This is where the command is initiated using subprocess
command = Popen(cmd)
text = command.stdout.read().decode("ascii") 
print(text)
with open("file.txt","w") as f:
f.write(text)
return (cmd)

错误

[2020-04-06 19:36:46,828] ERROR in app: Exception on /storageaccountcreate [POST]
Traceback (most recent call last):
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflaskapp.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflaskapp.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflaskapp.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflask_compat.py", line 39, in reraise
raise value
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflaskapp.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsite-packagesflaskapp.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "c:UsersPP284QZDesktoprepoms-identity-python-webapp-masterapp.py", line 67, in storageaccountcreate
command = Popen(cmd)
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsubprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "C:UsersPP284QZAppDataLocalProgramsPythonPython38-32libsubprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
File "c:UsersPP284QZ.vscodeextensionsms-python.python-2020.3.71659pythonFileslibpythondebugpyno_wheelsdebugpy_vendoredpydevd_pydev_bundlepydev_monkey.py", line 631, in new_CreateProcess
return getattr(_subprocess, original_name)(app_name, cmd_line, *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified

我在这里做错了什么?

您可以更改Popen的代码,如下所示:

command = Popen(cmd, shell=True, stdout=PIPE)
out, err = command.communicate()
text = out.decode("UTF-8")

最新更新