使用os.popen在python中创建列表 [英] Creating a list in python using os.popen
问题描述
以前,我已经能够使用类似于以下命令来创建列表:
Previously, I have been able to create lists using a command similar to the following:
os.popen('ls *.fits > samplelist')
现在,我正尝试通过按编号分组将文件整理到列表中.
Now I'm attempting to organize the files into lists by grouping them by number.
文件命名如下:
名称_0000_J.fits,名称_0001_J.fits,名称_0002_J.fits等
我试图运行此行代码,但它只是创建列表 skylist_J_1 并将其留空.
I've attempted to run this line of code but it just creates the list skylist_J_1 and leaves it empty.
os.popen('for num in {0000..0089} ; do ls Name_$num\_J.fits >> skylist_J_1 ; done')
我在命令行中运行了以上命令,它运行完美.任何见识将不胜感激.
I ran the above in a command line and it works perfectly. Any insight would be greatly appreciated.
我想出了这个解决方案,但它体积很大.希望有一种更清洁的方式来完成此任务.
I have come up with this solution but it is rather bulky. Hopefully there is a cleaner way to accomplish this.
def MkSkylist(qmin,qmax,name,band,quadrant):
a = qmax-qmin+1
ran = np.arange(qmin,qmax+1)
num = [0]*a
i = 0
while i < a:
num[i] = np.array2string(ran[i]).zfill(4)
i = i + 1
os.popen('ls '+name+num[0]+'_'+band+'.fits > skylist_'+band+'_'+quadrant)
i = 1
while i < a:
os.popen('ls '+name+num[0]+'_'+band+'.fits >> skylist_'+band+'_'+quadrant)
i = i + 1
推荐答案
问题似乎与for循环的语法有关:即使该语法在bash中有效,但Python似乎并不喜欢它.甚至没有subprocess.Popen(..., shell=True)
.
The problem seems to be with the syntax of the for loop: even though that syntax is valid in bash, it seems Python doesn't like it. Not even with subprocess.Popen(..., shell=True)
.
因此,请尝试改用 seq :
os.popen("for num in $(seq 0 89); do printf "Name_%04dJ.fits\n" $num >> skylist_J_1; done");
将生成具有以下内容的文件skylist_J_1
:
Which generates a file skylist_J_1
with this content:
Name_0001J.fits
Name_0002J.fits
Name_0003J.fits
Name_0004J.fits
...
Name_0086J.fits
Name_0087J.fits
Name_0088J.fits
Name_0089J.fits
还请注意,您可以将文件重定向放在外面,这与您的第一个示例更相似(使用>
代替>>
):
Also notice you can put the file redirection outside, which is more similar to your first example (using >
instead of >>
):
os.popen('for num in $(seq 0 89); do printf "Name_%04dJ.fits\n" $num; done > skylist_J_1')
这篇关于使用os.popen在python中创建列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!