问题:
在让我输入 Azure Powershell 命令之前,子进程终端不会保持打开状态并注销 Azure 服务帐户。
Python代码
import subprocess
Login = subprocess.Popen(['powershell', '-command', 'Connect-PowerBIServiceAccount'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
Workspaces = subprocess.Popen(['powershell', '-command', 'Get-PowerBIWorkspace'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# PowerShell command to get all activities for the past 30 days
ps_get_activities_cmd = '''
$enddate = get-date
$startdate = $enddate.AddDays(-30)
$startdateformat = "yyyy-MM-ddTHH:mm:ss"
$enddateformat = "yyyy-MM-ddT23:59:59"
for ($x = $startdate.AddDays(1); $x -lt $enddate; $x=$x.AddDays(1))
{
Write-Output ","
Get-PowerBIActivityEvent -StartDateTime $x.ToString($startdateformat) -EndDateTime $x.ToString($enddateformat)
}
'''
# Store PowerShell output into a variable
ps_activity_output = subprocess.run(['powershell', '-command', ps_get_activities_cmd], capture_output=True, text=True)
您可以看到我正在通过 Azure Powershell 登录,但是由于终端关闭,我无法向同一终端输入更多命令来存储不同的结果。
期待
使用类似于保持终端打开的子进程来保持输入命令。由于 Azure 服务帐户的需要,这是必需的。
期望 使用类似于保持终端打开的子进程来继续输入命令。
您可以使用下面的代码来执行相同的操作:
import subprocess as sp
rithwik_b = sp.Popen(['powershell', '-command', 'Connect-AzAccount -subscriptionid "b83c1ed3"'], stdin=sp.PIPE, stdout=sp.PIPE, text=True)
rithwik_b1 = sp.Popen(['powershell', '-command', 'Get-AzResourceGroup -Name "xxx"'], stdin=sp.PIPE, stdout=sp.PIPE, text=True)
while True:
user_input = input("Rithwik enter a PowerShell command (or type 'exit' to quit the terminal): ")
if user_input.lower() == 'exit':
rithwik_b.stdin.write('exit\n')
rithwik_b1.stdin.write('exit\n')
break
if not rithwik_b.stdin.closed and not rithwik_b1.stdin.closed:
rithwik_b.stdin.write(user_input + '\n')
rithwik_b1.stdin.write(user_input + '\n')
result = rithwik_b.communicate()[0]
print(result)
result1 = rithwik_b1.communicate()[0]
print(result1)
rithwik_b.wait()
rithwik_b1.wait()
Output:
两个命令均已执行:
您可以根据您的需求集成Power Bi命令。