使用PyQt5 GUI在终端中运行命令

时间:2018-03-15 12:08:54

标签: python pyqt5

我有这段代码:

from subprocess import Popen, PIPE

class App(QtWidgets.QMainWindow):
def __init__(self):
    super().__init__()
    # Create some widgets
    self.setGeometry(500, 500, 300, 300)
    self.pushButton = QtWidgets.QPushButton(
        'Print', self)
    self.pushButton.setGeometry(20, 20, 260, 30)
    self.pushButton.clicked.connect(self.print_widget)
    xlabel = "Hello World"

def print_widget(self):
    p = Popen('echo "This is a test." + xlabel | lpr', shell=True, stdout=PIPE, stderr=PIPE)
    out, err = p.communicate()

app = QtWidgets.QApplication(sys.argv)
gui = App()
gui.show()
app.exec_()

单击按钮时,终端将执行命令:

echo "This is a test." + xlabel | lpr

,输出结果为:enter image description here

但我想要的输出是"这是一个测试。 Hello World"但显然我的语法错了,我需要帮助。

2 个答案:

答案 0 :(得分:1)

您需要更改此字符串以获取变量内容:

'echo "This is a test." %s | lpr' % (xlabel)

答案 1 :(得分:1)

这个怎么样:

cmd = 'echo "This is a test. "' + xlabel + ' | lpr'
p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE)
相关问题