Python 中的系统 vs 调用 vs popen [英] system vs call vs popen in Python
本文介绍了Python 中的系统 vs 调用 vs popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
cmd = 'touch -d '+date_in+' '+images_dir+'/'+photo_name
os.system(cmd)
不起作用
subprocess.call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
不起作用
subprocess.Popen(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
有效!
为什么?在前两种情况下我遗漏了什么?
Why? What am I missing in first two cases?
pi@raspberrypi:~ $ python --version
Python 2.7.13
实际代码片段:
try:
response = urllib2.urlopen(url)
if(response.getcode() == 200):
photo_file = response.read()
with open(images_dir+'/'+photo_name,'wb') as output:
output.write(photo_file)
#cmd = 'touch -d '+date_in+' '+images_dir+'/'+photo_name
#subprocess.Popen(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
subprocess.check_call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
with open(images_dir+'/captions/'+photo_name+'.txt','wb') as output:
output.write(photo_title)
else:
print 'Download error'
except Exception as message:
print 'URL open exception {}'.format(message)
推荐答案
现在很清楚了:
with open(images_dir+'/'+photo_name,'wb') as output:
output.write(photo_file)
#cmd = 'touch -d '+date_in+' '+images_dir+'/'+photo_name
#subprocess.Popen(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
subprocess.check_call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
我的假设是:你仍然在 with
块中,所以如果 check_call
或 system
被执行,它结束,然后文件被关闭,再次设置日期并破坏 touch
工作.
My assumption is: you're still in the with
block, so if check_call
or system
is performed, it ends, then the file is closed, setting the date again and ruining touch
efforts.
使用Popen
,进程在后台执行,所以当它执行时,文件已经关闭(嗯,实际上这是一个竞争条件,不能保证)
With Popen
, the process is performed in the background, so when it's executed, the file is already closed (well, actually it's a race condition, it's not guaranteed)
我建议:
with open(images_dir+'/'+photo_name,'wb') as output:
output.write(photo_file)
subprocess.check_call(['touch','-d','{}'.format(date_in),'{}'.format(images_dir+'/'+photo_name)])
所以当你调用 check_call
写得更好:
fullpath = os.path.join(images_dir,photo_name)
with open(fullpath ,'wb') as output:
output.write(photo_file)
# we're outside the with block, note the de-indentation
subprocess.check_call(['touch','-d','{}'.format(date_in),fullpath])
这篇关于Python 中的系统 vs 调用 vs popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文