使用Python subprocess.call调用时,如何去除行末的\n字符?
解决读取文件换行符导致的subprocess解密错误
嘿,作为编程新手碰到这种细节问题太正常啦!你遇到的错误确实是因为读取每行数据时,末尾自带的\n换行符被当成了编码数据的一部分传给了解密命令,导致命令无法正确识别输入。下面给你几种简单靠谱的解决方法:
方法1:用strip()快速清理首尾空白
strip()会移除字符串首尾所有空白字符(包括换行符\n、空格、制表符等),如果你的编码数据本身不会在首尾包含空白字符,这是最省事的选择:
#!/usr/bin/env python3 import os import subprocess path = "/path" key = os.environ.get("KEY") file = input("Filename?: ") # 推荐用with语句自动管理文件,避免忘记关闭 with open(file, "r") as infile: for line in infile: # 清理掉换行符和首尾多余空白 cleaned_data = line.strip() subprocess.call([path, "decrypt", "-d", cleaned_data, "-k", key])
方法2:用rstrip('\n')精准移除换行符
如果你担心strip()会误删数据首尾的合法空格(虽然编码数据一般不会有这种情况),可以用rstrip('\n')只移除末尾的换行符,其他字符完全保留:
#!/usr/bin/env python3 import os import subprocess path = "/path" key = os.environ.get("KEY") file = input("Filename?: ") with open(file, "r") as infile: for line in infile: # 只去掉末尾的换行符,不碰其他内容 cleaned_data = line.rstrip('\n') subprocess.call([path, "decrypt", "-d", cleaned_data, "-k", key])
方法3:一次性读取所有行并自动去换行
用read().splitlines()可以一次性读取文件所有内容,自动分割成不带换行符的行列表,适合文件不大的场景:
#!/usr/bin/env python3 import os import subprocess path = "/path" key = os.environ.get("KEY") file = input("Filename?: ") with open(file, "r") as infile: # splitlines()会自动去掉每行的换行符 lines = infile.read().splitlines() for line in lines: subprocess.call([path, "decrypt", "-d", line, "-k", key])
另外小提醒:尽量用with语句打开文件,它会在代码块结束后自动关闭文件,比手动调用close()更安全省心哦!
内容的提问来源于stack exchange,提问作者jayteezer
相关产品推荐
相关产品推荐

