python os popen用法_使用os.popen在python中创建列表

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.

The files are named as following:

Name_0000_J.fits, Name_0001_J.fits, Name_0002_J.fits, ect.

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.

Edit:

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

解决方案

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).

So, try using seq instead:

os.popen("for num in $(seq 0 89); do printf "Name_%04dJ.fits\n" $num >> skylist_J_1; done");

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')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值