简体   繁体   English

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

[英]Running a Command in Terminal Using PyQt5 GUI

I have this code: 我有以下代码:

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_()

When the push button is clicked, the terminal will execute the command: 单击按钮后,终端将执行以下命令:

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

and the output will be: 输出将是: 在此处输入图片说明

But the Output I want is "This is a test. Hello World" but obviously my syntax is wrong and I need help. 但是我想要的输出是“ This is a test。Hello World”,但是显然我的语法是错误的,我需要帮助。

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

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

What about this: 那这个呢:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM