[英]Using ls in Python subprocess.Popen function
proc = subprocess.Popen(['ls', '-v', self.localDbPath+'labris.urls.*'], stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line != '':
print line
else:
break
When using the above code I get the error saying: 当使用上面的代码时,我得到错误提示:
ls: /var/lib/labrisDB/labris.urls.*: No such file or directory
But when I dıo the same from shell I get no errors: 但是,当我在shell中执行相同操作时,我没有得到任何错误:
ls -v /var/lib/labrisDB/labris.urls.*
Also this doesn't give any error either: 同样,这也不会产生任何错误:
proc = subprocess.Popen(['ls', '-v', self.localDbPath], stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line != '':
print line
else:
break
Why is the first code failing? 为什么第一个代码失败? What am I missing? 我想念什么?
You get error because python subprocess could not be able to expand * like bash . 您会收到错误消息,因为python 子进程无法像bash一样扩展*。
Change your code like that: 像这样更改代码:
from glob import glob
proc = subprocess.Popen(['ls', '-v'] + glob(self.localDbPath+'labris.urls.*'), stdout=subprocess.PIPE)
Here is more information about glob expansion in python and solutions: Shell expansion in Python subprocess 以下是有关python中的glob扩展和解决方案的更多信息: Python子进程中的Shell扩展
Globbing is done by the shell. 球形由外壳完成。 So when you're running ls *
in a terminal, your shell is actually calling ls file1 file2 file3 ...
. 因此,当您在终端中运行ls *
时,您的外壳实际上是在调用ls file1 file2 file3 ...
If you want to do something similar, you should have a look at the glob
module, or just run your command through a shell: 如果要执行类似的操作,则应查看glob
模块,或仅通过shell运行命令:
proc = subprocess.Popen('ls -v ' + self.localDbPath + 'labris.urls.*',
shell=True,
stdout=subprocess.PIPE)
(If you choose the latter, be sure to read the security warnings !) (如果选择后者,请务必阅读安全警告 !)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.