Python和Tar命令 shell=True

4 投票
2 回答
7634 浏览
提问于 2025-04-17 09:52

我写了一个脚本来打包一些备份:

date = str(now.year)+str(now.month)+str(now.day)
tar="tar -pczf "+date+"backup_lucas.tar.gz /home/lucas/backup/"
subprocess.Popen(tar)

但是我遇到了这个问题:

  File "test.py", line 21, in <module>
    subprocess.Popen(tar)
  File "/usr/lib/python2.6/subprocess.py", line 623, in __init__
    errread, errwrite)
  File "/usr/lib/python2.6/subprocess.py", line 1141, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

当我在 Popen 命令中加上 shell=True 时,它就能正常工作:

subprocess.Popen(tar,shell=True)

不过我听说使用 shell=True 有时不安全,所以应该避免使用。

那我该怎么做才能在不使用 shell=True 的情况下成功执行这个命令呢?

2 个回答

2

@sgallen 的回答是从根本上说是正确的。不过补充一点:你可能会发现指定“tar”命令的绝对路径也很有用,比如 subprocess.Popen(['/usr/sbin/tar', ...]。这个路径的位置当然是根据你使用的 Linux 版本而定的。

10

当shell=False时,你需要通过一个列表来传递你的命令:

date = str(now.year)+str(now.month)+str(now.day)
filename = date + "backup_lucas.tar.gz"
subprocess.Popen(['tar', '-pczf', filename, '/home/lucas/backup/'])

补充说明:文档中重要的部分:

“在Unix系统中,当shell=False(默认设置)时:在这种情况下,Popen类使用os.execvp()来执行子程序。args通常应该是一个序列。如果args指定为一个字符串,它将被用作要执行的程序的名称或路径;这只有在程序没有传递任何参数时才有效。” - http://docs.python.org/library/subprocess.html#popen-constructor

撰写回答