我想在python中运行sudo来打开一个应用程序

例如,如果我想对我的python脚本调用突触,这是我所尝试的,但是我得到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的值应该是一个字节字符串…

你把错误的观点传递给了Popen 。 文档在这里: https : //docs.python.org/3/library/subprocess.html#popen-constructor

甚至更容易…只需使用subprocess模块提供的call函数:

 subprocess.call(['sudo', 'synaptic'])