如何使您的OWN控制台像Windows命令提示符

时间:2018-05-28 09:41:28

标签: python python-3.x subprocess pycharm pyqt5

正如你在PyCharm中看到的, 最先进的控制台,我正在尝试制作一个 请告诉我该怎么做。

我知道 subprocess 模块对于这种情况非常方便。

我有一个名为 add.exe 的exe文件 该 add.exe 文件的 Python 3x 中的代码将是,

a = input('Enter 1st Number')
b = input('Enter 2nd Number')
print('a + b =', a + b)

现在当我使用子进程在后台运行它并获取输出然后提供输入时,我只得到一个大的黑色空控制台屏幕。 My Console Window 哦!这看起来很难看。

我只想获取输出并在程序需要输入时获得提示但是 无需打开控制台 我的代码到目前为止,

from subprocess import Popen, PIPE
p = Popen(['add.exe'],
          stdout=PIPE,
          stdin=PIPE,
          )
p.stdin.write(b'4')
p.stdin.write(b'6')
print(p.stdout.read())

然后我得到了那个愚蠢的控制台 当我关闭那个控制台时,我得到了IDLE上的输出,

b'输入第一个号码:'

我该怎么办!! 有些人请帮帮忙。

1 个答案:

答案 0 :(得分:1)

console.py

#!/usr/bin/env python3

from subprocess import check_output, PIPE

commands = ['add.exe', 'sub.exe', 'print', 'exit', 'quit']

# Only commands with a set number of arguments
num_cmd_args = {
    'add.exe': 2,
    'sub.exe': 2
}

# Command help messages
cmd_helps = {
    'add.exe': 'Adds 2 numbers together. Returns num1 + num2',
    'sub.exe': 'Subtracts 2 numbers. Returns num1 - num2',
    'print': 'Prints all arguments passed'
}

while True:
    user_in = input('$ ').split()
    cmd = user_in[0]
    args = user_in[1:]
    # Default to '*' if not cmd not found in num_cmd_args
    n_args_needed = num_cmd_args.get(cmd, '*')

    # Check cmd
    if cmd not in commands:
        print('command not found:', cmd)
        continue
    elif cmd in ('exit', 'quit'):
        break

    # To make this much better, you're probably going to want to
    #  do some type checking to make sure that the user entered
    #  numbers for commands like add.exe and sub.exe. I suggest
    #  also looking at word splitting and maybe escaping special
    #  characters like \x07b or \u252c.

    # Check cmd's args
    if n_args_needed != len(args):
        print(cmd_helps[cmd])
    elif n_args_needed in ('*', num_cmd_args[cmd]):
        out = check_output(['./'+cmd, *args])
        print(out.decode(), end='')

这些是我的c ++文件:


add.cpp

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    cout << atoi(argv[1]) + atoi(argv[2]) << endl;
    return 0;
}


sub.cpp

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    cout << atoi(argv[1]) - atoi(argv[2]) << endl;
    return 0;
}


print.cpp

#include <iostream>
using namespace std;

int main(int argc, char** argv) {
    for (int i=1; i<argc; i++)
        cout << argv[i] << endl;
    return 0;
}