首页 > 解决方案 > 如何使用子进程读取键盘输入并写入文件?

问题描述

我使用子进程运行命令。这是我的代码。

subprocess_using_popen.py

out_f = open("output_file.txt", "w")
file_path = "../Python_tests/display_alphabet_type.py"
cmd = ['python3', file_path]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,\
    #stdin=subprocess.PIPE,\
    stderr=subprocess.STDOUT,\
    universal_newlines = True
)
for line in proc.stdout:
    sys.stdout.write(line) #on console
    out_f.write(line)      #to file
#out_f.write(stdout)
out_f.write("Return code: {0}\n". format(proc.returncode))
out_f.close()

在这里,我从键盘输入。我希望将此输入与我的标准输出一起写入输出文件。如何才能做到这一点?

#display_alphabet_type.py

def display_digits_chars_symbols_in_string(str):

    count_lowercase = 0
    count_uppercase = 0
    count_digit = 0
    count_special_characters = 0
    d = dict()
    for char in str:
        if char.islower():
            count_lowercase += 1
        elif char.isupper():
            count_uppercase += 1
        #elif char in range(0, 9):
        elif char.isnumeric():
            count_digit += 1
        else:
            count_special_characters += 1

    d['count_lowercase'] = count_lowercase
    d['count_uppercase'] = count_uppercase
    d['count_digits'] = count_digit
    d['count_special_chars'] = count_special_characters
    return d

def main():
    #str = input("Enter string: ")
    print("Enter string: ")
    string = input(str())
    d = display_digits_chars_symbols_in_string(string)
    print(d)

if __name__== "__main__":
    main()
    exit(0)

我得到这个输出:

python3 subprocess_using_popen.py 

a123#  
Enter string:   
{'count_digits': 3, 'count_uppercase': 0, 'count_lowercase': 1, 'count_special_chars': 1}

cat output_file.txt

Enter string: 
{'count_digits': 0, 'count_uppercase': 0, 'count_lowercase': 1, 'count_special_chars': 0}
Return code: 0

在这里,在 output_file 中,输入的字符串没有被复制到文件中。如何将键盘输入的字符串复制到该文件中?

标签: python-3.xsubprocess

解决方案


推荐阅读