Python 和 Tar 命令 shell=True

4

我编写了这个脚本来压缩一些备份文件:

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个回答

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


2

@sgallen的答案基本正确。但是作为额外的说明:您可能还会发现指定“tar”命令的绝对路径很有用,例如subprocess.Popen(['/usr/sbin/tar', ...]。当然,它所在的位置是特定于您的Linux版本的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接