在子流程中调用列表项
Calling list items in subprocess
我正在尝试使用 subprocess.call 调用列表时间。似乎它不起作用。任何更好的方法来做到这一点。
import os, sys
import subprocess as sb
files_to_remove=['*.jpg','*.txt','*.gif']
for item in files_to_remove:
try:
**sb.call(['rm' %s]) %item** # not working
except:
print 'no %s files in directory' %item
它没有按预期工作,因为它转义了参数。以及以下作品:
#!/usr/bin/python
import os, sys
import subprocess as sb
files_to_remove=['*.jpg','*.txt','*.gif']
for item in files_to_remove:
try:
sb.check_call(['rm ' + item], shell=True)
except sb.CalledProcessError as e:
print(e.output)
except:
print("unknown error")
这里不需要使用子进程
import glob
import os
files_to_remove = ['*.jpg', '*.txt', '*.gif']
for files_glob in files_to_remove:
for filename in glob.glob(files_glob):
os.remove(filename)
如果我们坚持使用子进程(我们不会删除这些文件),我们会这样做
import glob
import subprocess
files_to_remove=['*.jpg', '*.txt', '*.gif']
for files_glob in files_to_remove:
matches = glob.glob(files_glob)
if matches:
subprocess.check_call(['rm'] + matches)
else:
print 'no %s files in directory' % files_glob
最好永远不要使用 shell=True
。
我正在尝试使用 subprocess.call 调用列表时间。似乎它不起作用。任何更好的方法来做到这一点。
import os, sys
import subprocess as sb
files_to_remove=['*.jpg','*.txt','*.gif']
for item in files_to_remove:
try:
**sb.call(['rm' %s]) %item** # not working
except:
print 'no %s files in directory' %item
它没有按预期工作,因为它转义了参数。以及以下作品:
#!/usr/bin/python
import os, sys
import subprocess as sb
files_to_remove=['*.jpg','*.txt','*.gif']
for item in files_to_remove:
try:
sb.check_call(['rm ' + item], shell=True)
except sb.CalledProcessError as e:
print(e.output)
except:
print("unknown error")
这里不需要使用子进程
import glob
import os
files_to_remove = ['*.jpg', '*.txt', '*.gif']
for files_glob in files_to_remove:
for filename in glob.glob(files_glob):
os.remove(filename)
如果我们坚持使用子进程(我们不会删除这些文件),我们会这样做
import glob
import subprocess
files_to_remove=['*.jpg', '*.txt', '*.gif']
for files_glob in files_to_remove:
matches = glob.glob(files_glob)
if matches:
subprocess.check_call(['rm'] + matches)
else:
print 'no %s files in directory' % files_glob
最好永远不要使用 shell=True
。