sb.AppendLine写错了而不是代码

时间:2017-06-01 19:40:32

标签: batch-file

我有一个表单,当您单击提交按钮时,该表单应该创建批处理文件。批处理将提升UAC提示允许用户以管理员身份使用..但问题是我与sb.AppendLine("""%temp%\ getadmin.vbs&#34) ;"")在我的代码中。它一直处于FALSE"%temp%\ getadmin.vbs"应该在我的批处理文件中。请帮忙!哈哈,我不知道自己做错了什么

class Window(QDialog):
  def __init__(self, parent=None):
    super(Window, self).__init__(parent)

    self.log_x = np.array([])
    self.log_y = np.array([])
    self.test_id = ''
    self.plot_thread = PlotThread()
    self.plot_thread.main = self
    self.figure = plt.figure()

    # Canvas Widget
    self.canvas = FigureCanvas(self.figure)

    # Navigation Widget
    self.toolbar = NavigationToolbar(self.canvas, self)

    # Button to control plot function
    self.control_plot = QPushButton('Start')
    self.control_plot.clicked.connect(self.plot)

    # Button to log data
    self.log_data = QPushButton('Log')
    self.log_data.clicked.connect(self.log_file)

    # Progress bar to indicate data harvesting speed
    self.progressBar = QProgressBar(self)
    self.progressBar.setGeometry(QRect(10, 10, 200, 25))
    self.progressBar.move(500, 10)

    # Layout
    layout = QVBoxLayout()
    layout.addWidget(self.toolbar)
    layout.addWidget(self.canvas)
    layout.addWidget(self.control_plot)
    layout.addWidget(self.log_data)
    self.setLayout(layout)

    # Initialising the plot figure
    self.fig1 = self.figure.add_subplot(111)
    rect = self.fig1.patch
    rect.set_facecolor('white')
    self.fig1.set_xlabel('time [s]')
    self.fig1.set_ylabel('RSSI [dBm]')
    self.fig1.grid(True)
    self.fig1.spines["top"].set_visible(False)
    self.fig1.spines["right"].set_visible(False)
    self.fig1.spines["bottom"].set_visible(False)
    self.fig1.spines["left"].set_visible(False)

  def log_file(self):
    directory = ''.join(filter(str.isalpha, self.test_id))

    # Creating the directory if it doesn't exist
    create_directory(directory)

    # Creating the file if it doesn't exist
    if not os.path.isfile(
            'C:\\Users\\Simon\\Documents\\Ete2017\\PythonCode\\main\\{0}\\{1}.txt'.format(directory,
                                                                                         self.test_id)):
        log = open('C:\\Users\\Simon\\Documents\\Ete2017\\PythonCode\\main\\{0}\\{1}.txt'.format(directory,
                                                                                               self.test_id),
                   'w')
        # Creating the header
        log.write(' ' * 9 + 'Time [s]' + ' ' * 9 + '|' + ' ' * 4 + 'RSSI [dBm] \n')
    else:
        log = open('C:\\Users\\Simon\\Documents\\Ete2017\\PythonCode\\main\\{0}\\{1}.txt'.format(directory,
                                                                                               self.test_id),
                   'a')

    # Logging the data
    for i in range(np.size(self.log_x)):
        x = str(self.log_x[i])
        space_num = 24 - len(x)
        log.write(' ' * space_num + x + "  |" + ' ' * 5 + str(self.log_y[i]) + ' \n')

    # Reinitialising logging
    self.log_x = np.array([])
    self.log_y = np.array([])

  def pause(self):
    self.plot_thread.terminate()
    self.control_plot.setText('Start')
    self.control_plot.clicked.connect(self.plot)
    self.log_data.setText('Log')
    self.log_data.clicked.connect(self.log_file)

  def plot(self):
    self.control_plot.setText('Pause')
    self.control_plot.clicked.connect(self.pause)
    self.log_data.setText('')
    self.log_data.clicked.connect(self.wait)

    self.plot_thread.start()

  def wait(self):
    pass

class PlotThread(QThread):
    def __init__(self):
        QThread.__init__(self)
        self.main = ''
        self.t_start = 0
        self.ser = ser

        # Replace by expected values at time 0s
        self.xf = 0
        self.yf = -43

    def run(self):
        while self.isRunning():
            print("Starting to plot")
            self.ser.flushInput()
            self.t_start = time.time()
            # Preallocating memory for the arrays
            x = np.empty([100])
            y = np.empty([100])

            # Initializing start values
            x[0] = self.xf
            y[0] = self.yf
            self.main.progressBar.setValue(1)

            # Reading data from the Arduino
            for i in range(99):
                reading = str(ser.readline())
                while not reading[3:5].isdigit():
                    reading = str(ser.readline())
                y[i + 1] = -int(reading[3:5])
                x[i + 1] = self.xf + (time.time() - self.t_start)
                print(x[i])
                self.main.progressBar.setValue(i + 1)

            # Preparing start values for next iteration
            self.xf = x[99]
            self.yf = y[99]

            # Preparing the log variables
            self.main.log_x = np.append(self.main.log_x, x)
            self.main.log_y = np.append(self.main.log_y, y)

            # Plotting raw data
            self.main.fig1.plot(x, y, 'r--')

            # Filtering raw data
            poly8 = np.polyfit(x, y, 8)
            xGraph = np.linspace(x[0], x[99], num=200)
            yGraph = np.polyval(poly8, xGraph)

            # Graphing filtered data
            self.main.fig1.plot(xGraph, yGraph, 'b')
            # Saving the graph into a file
            timer = self.xf + time.time() - self.t_start
            # Scaling the axes
            if timer > 80:
                print("Scaling the axes")
                self.main.fig1.set_xlim([int(timer) - 80, timer])

            # refresh canvas
            self.main.canvas.draw()
            self.main.canvas.flush_events()

1 个答案:

答案 0 :(得分:0)

我将sb.AppendLine("设置params =%:" ="""")更改为sb.AppendLine(&# 34;设置params =%:"" =""""")并且它有效。我无法相信这很简单。守则必须一起成长。非常感谢你的帮助:)我发布了更新的代码,万一有人可能希望将来使用它。

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click


    Dim sb As New System.Text.StringBuilder

    sb.AppendLine("@echo off")
    sb.AppendLine("")
    sb.AppendLine(":: BatchGotAdmin")
    sb.AppendLine(":-------------------------------------")
    sb.AppendLine("REM  --> Check for permissions")
    sb.AppendLine(">nul 2>&1 ""%SYSTEMROOT%\system32\cacls.exe"" ""%SYSTEMROOT%\system32\config\system""")
    sb.AppendLine("")
    sb.AppendLine("REM --> If error flag set, we do not have admin.")
    sb.AppendLine("if '%errorlevel%' NEQ '0' (")
    sb.AppendLine("   echo Requesting administrative privileges...")
    sb.AppendLine("    goto UACPrompt")
    sb.AppendLine(") else ( goto gotAdmin )")
    sb.AppendLine(":UACPrompt")
    sb.AppendLine("    echo Set UAC = CreateObject^(""Shell.Application""^) > ""%temp%\getadmin.vbs""")
    sb.AppendLine("set params = %*:""="""" ")
    sb.AppendLine("    echo UAC.ShellExecute ""cmd.exe"", ""/c %~s0 %params%"", """", ""runas"", 1 >> ""%temp%\getadmin.vbs""")
    sb.AppendLine("""%temp%\getadmin.vbs"" ")
    sb.AppendLine("    del ""%temp%\getadmin.vbs""")
    sb.AppendLine("    exit /B")
    sb.AppendLine("")
    sb.AppendLine(":gotAdmin")
    sb.AppendLine("    pushd ""%CD%""")
    sb.AppendLine("    CD /D ""%~dp0""")
    sb.AppendLine(":--------------------------------------")
    sb.AppendLine("pause")

    IO.File.WriteAllText(Environ("SystemDrive") + "\fileName.bat", sb.ToString())



End Sub
End Class