gpt4 book ai didi

python - 我正在尝试在 python 中运行 sudo 来打开一个应用程序

转载 作者:太空狗 更新时间:2023-10-29 12:25:40 25 4
gpt4 key购买 nike

例如,如果我想在我的 python 脚本上调用 synaptic,这就是我尝试的方法,但 Popen 出现错误。有没有办法用 sudo 而不是 gksu 来完成这项工作?我想使用这种方法在更大的程序中运行脚本。

process = subprocess.Popen("sudo synaptic", 'w', stdout=subprocess.PIPE, bufsize=1).write(password)
TypeError: __init__() got multiple values for keyword argument 'bufsize'

下面是我正在使用的

from PyQt4 import QtGui, QtCore
import os
import sys
import subprocess
# from mainwindow import Ui_MainWindow

class PasswordDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(PasswordDialog, self).__init__(parent)
PasswordDialog.resize(self, 375, 130)
PasswordDialog.setWindowTitle(self, "Enter Password")
self.buttonOk = QtGui.QPushButton(self)
self.buttonOk.setText("OK")
self.buttonCancel = QtGui.QPushButton(self)
self.buttonCancel.setText("Cancel")
self.textEdit = QtGui.QLineEdit(self)
self.textEdit.setFocus()

self.label = QtGui.QLabel(self)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.label.setFont(font)
self.label.setText("Enter your password to perform administrative Tasks")
self.label.setWordWrap(True)
self.label_2 = QtGui.QLabel(self)
self.label_2.setText("Password")
self.verticalLayout = QtGui.QVBoxLayout(self)
self.verticalLayout.addWidget(self.label)
self.horizontalLayout = QtGui.QHBoxLayout(self)
self.horizontalLayout.addWidget(self.label_2)
self.horizontalLayout.addWidget(self.textEdit)
self.verticalLayout.addLayout(self.horizontalLayout)
self.horizontalLayout2 = QtGui.QHBoxLayout(self)
self.horizontalLayout2.setAlignment(QtCore.Qt.AlignRight)
self.horizontalLayout2.addWidget(self.buttonCancel)
self.horizontalLayout2.addWidget(self.buttonOk)
self.verticalLayout.addLayout(self.horizontalLayout2)
self.buttonOk.clicked.connect(self.handleLogin)
self.buttonCancel.clicked.connect(self.close)

def handleLogin(self):
password = self.textEdit.text()
process = subprocess.Popen("sudo synaptic", 'w').write(password)
#out = process.stdout.read(1)
try:
subprocess.check_call(process)
except subprocess.CalledProcessError as error:
print "error code", error.returncode, error.output



if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
login = PasswordDialog()

if login.exec_() == QtGui.QDialog.Accepted:
window = Window()
window.show()
sys.exit(app.exec_())

最佳答案

我认为您应该使用communicate 将密码发送到sudo 命令。

试试这个:

import subprocess

with subprocess.Popen(["sudo", "synaptic"], stdout=subprocess.PIPE, bufsize=1) as process:
process.communicate(password)
process.wait()

process 的值应该是字节串……

关于python - 我正在尝试在 python 中运行 sudo 来打开一个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41646077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com