python-3.x - 如何使用子进程读取键盘输入并写入文件?
问题描述
我使用子进程运行命令。这是我的代码。
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 中,输入的字符串没有被复制到文件中。如何将键盘输入的字符串复制到该文件中?
解决方案
推荐阅读
- node.js - 我正在尝试在 linux kubuntu 上安装 gulp 但我有这样的问题
- android - 如何正确使用 JobService?
- laravel - 如何获取列中具有相同值的数据的计数
- cordova - 如何在适用于 Android 和 iOS 的 Ionic4 上启用 webRTC 到 InAppBrowser 应用程序?
- dart - 如何在颤振中构建这种类型的搜索栏?
- datagridview - 双击 DataGridViewrow 以其他形式永久显示 datagrv 中的新数据
- javascript - 避免嵌套函数,谷歌云函数
- rpa - Blue Prism - 在 SAP SPY MODE 文本字段中写入错误
- algorithm - 快速排序分区的循环不变量
- javascript - React - 在构造函数中绑定 this 不起作用