reading and writing to QProcess in Qt Console Application

后端 未结 1 355
自闭症患者
自闭症患者 2020-12-22 00:28

Noted: this appears to be a specific issue question but hopefully it can be edited for all to related to

I need to interact with a QProcess object.

相关标签:
1条回答
  • 2020-12-22 00:52

    Unfortunately I don't have all your code, so I made an example. I hope it helps you.

    If I compare my code to yours, I think the problem could be you are not calling readAllStandardOutput() after writing or maybe you are not calling exec() in your main.cpp.

    #include <QCoreApplication>
    #include <QProcess>
    #include <QDebug>
    
    class MyProcess : public QProcess
    {
        Q_OBJECT
    
    public:
        MyProcess(QObject *parent = 0);
        ~MyProcess() {}
    
    public slots:
        void myReadyRead();
        void myReadyReadStandardOutput();
    };
    
    MyProcess::MyProcess(QObject *parent)
    {
        connect(this,SIGNAL(readyRead()),
                this,SLOT(myReadyRead()));
        connect(this,SIGNAL(readyReadStandardOutput()),
                this,SLOT(myReadyReadStandardOutput()));
    }
    
    void MyProcess::myReadyRead() {
        qDebug() << Q_FUNC_INFO;
    }
    
    void MyProcess::myReadyReadStandardOutput() {
        qDebug() << Q_FUNC_INFO;
        // Note we need to add \n (it's like pressing enter key)
        this->write(QString("myname" + QString("\n")).toLatin1());
        // Next line no required
        // qDebug() << this->readAll();
        qDebug() << this->readAllStandardOutput();
    
    }
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        MyProcess *myProcess = new MyProcess();
    
        QString program = "/home/fran/code/myscript.sh";
    
        myProcess->start("/bin/sh", QStringList() << program);
    
        a.exec();
    }
    
    #include "main.moc"
    

    Script to test the application:

    echo "enter your name:"
    read n
    if [ ! -z "$n" ];
    then
        echo "success"
        exit 0;
    else
        echo "failed"
        exit 1;
    fi
    
    0 讨论(0)
提交回复
热议问题