在多个python线程上运行powershell

2024-10-01 07:13:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用Python做的备份软件。这个备份软件列出了网络上的所有计算机,我需要将这些计算机备份到给定的目录。我的想法是:当用户在某台计算机上单击backup时,它会启动一个线程,在该线程中执行Powershell脚本,并显示百分比((已复制的字节数/要复制的总字节数)*100)。一切正常,我可以复制一台电脑没有问题

但问题是:每当我启动第二个线程(在另一台计算机上单击“备份”)时,似乎Powershell的进程停止了,因为没有更多的输出,唯一正在运行的进程是在第二个线程上启动的新Powershell进程

线程运行方法:

     def run(self):
        '''
        Initialise the runner function with passed args, kwargs.
        '''
        self.setAlive(True)
        p = subprocess.Popen(["powershell.exe",".\script.ps1 . .\\Backups"],stdout=subprocess.PIPE)
        self.signals.progress.emit(self.CurrentComp['RowIndex'], 0, self)
        percentage = 0.0
        a = ""
        displayPercentage = 0.0
        while a != "Done Copying":
            a = p.stdout.readline()
            a = a.decode("utf-8").strip()
            try:
                percentage = float(a)
                print(percentage)
                while displayPercentage != int(percentage):
                    displayPercentage += 1
                    sleep(0.03)
                    self.signals.progress.emit(self.CurrentComp['RowIndex'], displayPercentage ,self)
            except ValueError:
                pass

        self.signals.finished.emit()
Param([String[]]$paths,[String]$Destination)

function Copy-WithProgress {
    [CmdletBinding()]
    param (
            [Parameter(Mandatory = $true)]
            [string] $Source
        , [Parameter(Mandatory = $true)]
            [string] $Destination
        , [int] $Gap = 200
        , [int] $ReportGap = 2000
    )
    $RegexBytes = '(?<=\s+)\d+(?=\s+)';
    $CommonRobocopyParams = '/MIR /NP /NDL /NC /BYTES /NJH /NJS';
    $StagingLogPath = '{0}\temp\{1} robocopy staging.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd HH-mm-ss');
    $StagingArgumentList = '"{0}" "{1}" /LOG:"{2}" /L {3}' -f $Source, $Destination, $StagingLogPath, $CommonRobocopyParams;
    Start-Process -Wait -FilePath robocopy.exe -ArgumentList $StagingArgumentList -NoNewWindow;
    $StagingContent = Get-Content -Path $StagingLogPath;
    $TotalFileCount = $StagingContent.Count - 1;
    [RegEx]::Matches(($StagingContent -join "`n"), $RegexBytes) | % { $BytesTotal = 0; } { $BytesTotal += $_.Value; };
    $RobocopyLogPath = '{0}\temp\{1} robocopy.log' -f $env:windir, (Get-Date -Format 'yyyy-MM-dd HH-mm-ss');
    $ArgumentList = '"{0}" "{1}" /LOG:"{2}" /ipg:{3} {4}' -f $Source, $Destination, $RobocopyLogPath, $Gap, $CommonRobocopyParams;
    $Robocopy = Start-Process -FilePath robocopy.exe -ArgumentList $ArgumentList -Verbose -PassThru -NoNewWindow;
    Start-Sleep -Milliseconds 100;
    #region Progress bar loop
    while (!$Robocopy.HasExited) {
        Start-Sleep -Milliseconds $ReportGap;
        $BytesCopied = 0;
        $LogContent = Get-Content -Path $RobocopyLogPath;
        $BytesCopied = [Regex]::Matches($LogContent, $RegexBytes) | ForEach-Object -Process { $BytesCopied += $_.Value; } -End { $BytesCopied; };
        #Write-Verbose -Message ('Bytes copied: {0}' -f $BytesCopied);
        #Write-Verbose -Message ('Files copied: {0}' -f $LogContent.Count);
        $Percentage = 0;
        if ($BytesCopied -gt 0) {
           $Percentage = (($BytesCopied/$BytesTotal)*100)
        }
        Write-Host $Percentage
    }
    Write-Host "Done Copying"

Tags: selfget进程计算机备份线程destinationstart