Python 没有“\n”的子进程列表文件
Python subprocess list files without "\n"
我在 python 上使用 subprocess
列出一个文件夹中的所有 files/folders:
def subprocess_list(command):
p = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = p.communicate()[0].strip()
lista.append(proc_stdout.decode('utf-8'))
retcode = p.wait()
subprocess_list('ls | grep aa')
当我打印 "lista" 时,我得到了单元素列表中的所有路径:
lista=[aaa\naab\naac\n]
因此,为了将它们分开并获取每个文件,我首先将它们导出到 .txt,调用它并删除 \n
with open('%s/files.txt'%Path_Desktop,'w') as file:
for item in lista:
file.write(item)
with open('%s/files.txt'%Path_Desktop) as file:
content = file.readlines()
content = [x.strip() for x in content]
打印"content":
content=['aaa','aab','aac']
有没有办法不用导出部分直接做?提前致谢!
首先,你不能使用子进程来调用 ls。对于您的 purpose,glob 或 os 模块是更好的选择。
为什么会得到“\n”字符串?好吧,您只需调用一个子进程,它将 return 输出为字符串。
使用您的 suprocess-ls 解决方案,您现在可以继续将字符串拆分为“\n”,以获得真正的 python 列表。
list = list.split("\n")
改用 glob 会更好。 https://docs.python.org/3/library/glob.html
import glob
list = glob.glob("*aa*")
你会得到你想要的,但它是更快、更安全、pythonic 和更好的解决方案。
我为此更改了子流程,不知道是否正确或相同,但到目前为止它运行良好。
lista = (os.popen('ls | grep aa').read()).split('\n')
我在 python 上使用 subprocess
列出一个文件夹中的所有 files/folders:
def subprocess_list(command):
p = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
proc_stdout = p.communicate()[0].strip()
lista.append(proc_stdout.decode('utf-8'))
retcode = p.wait()
subprocess_list('ls | grep aa')
当我打印 "lista" 时,我得到了单元素列表中的所有路径:
lista=[aaa\naab\naac\n]
因此,为了将它们分开并获取每个文件,我首先将它们导出到 .txt,调用它并删除 \n
with open('%s/files.txt'%Path_Desktop,'w') as file:
for item in lista:
file.write(item)
with open('%s/files.txt'%Path_Desktop) as file:
content = file.readlines()
content = [x.strip() for x in content]
打印"content":
content=['aaa','aab','aac']
有没有办法不用导出部分直接做?提前致谢!
首先,你不能使用子进程来调用 ls。对于您的 purpose,glob 或 os 模块是更好的选择。
为什么会得到“\n”字符串?好吧,您只需调用一个子进程,它将 return 输出为字符串。
使用您的 suprocess-ls 解决方案,您现在可以继续将字符串拆分为“\n”,以获得真正的 python 列表。
list = list.split("\n")
改用 glob 会更好。 https://docs.python.org/3/library/glob.html
import glob
list = glob.glob("*aa*")
你会得到你想要的,但它是更快、更安全、pythonic 和更好的解决方案。
我为此更改了子流程,不知道是否正确或相同,但到目前为止它运行良好。
lista = (os.popen('ls | grep aa').read()).split('\n')