gpt4 book ai didi

python等待shell命令完成

转载 作者:太空狗 更新时间:2023-10-30 02:21:26 25 4
gpt4 key购买 nike

我正在运行脚本来解压缩一些文件,然后删除 rar 文件。我通过 shell 运行命令来做到这一点。我已经尝试了几种不同的方法让脚本等到文件解压完成,但它仍然继续并在文件被使用之前删除文件。

我已经尝试了下面的代码,这是不行的。我试图看看我是否能让 wait() 工作,但也没有运气。

有什么想法吗?运行 python 2.7

编辑:我希望脚本运行命令:)

            p = subprocess.Popen('unrar e ' + root + '/' + i + ' ' + testfolder,
bufsize=2048, shell=True,
stdin=subprocess.PIPE)
p.stdin.write('e')
p.communicate()

for root, dirs, files in os.walk(testfolder):
for i in files:

print 'Deleting rar files'
os.remove(i)

for i in os.listdir(testfolder):
if os.path.isdir(testfolder + i):
shutil.rmtree(testfolder + i)

最佳答案

这是邪恶的:

p = subprocess.Popen('unrar e ' + root + '/' + i + ' ' + testfolder,
bufsize=2048, shell=True, stdin=subprocess.PIPE)

相反,

p = subprocess.Popen(['unrar', 'e', '%s/%s' % (root, i), testfolder],
bufsize=2048, stdin=subprocess.PIPE)
p.stdin.write('e')
p.wait()
if p.returncode == 0:
pass # put code that must only run if successful here.

通过将一个精确的数组而不是一个字符串传递给 Popen 并且不使用 shell=True,一个包含空格的文件名不能被解释为更多而不是一个参数,或一个子 shell 命令,或其他一些潜在的恶意事物(想想一个名称中带有 $(rm -rf ..) 的文件)。

然后,在调用 p.wait() 之后(当您不捕获 stderr 或 stdout 时,不需要 p.communicate()),您必须检查p.returncode判断进程是否成功,只有p.returncode == 0(表示成功)才继续删除文件。

您的初步诊断是 p.communicate()unrar 进程仍在运行时返回,这是不可行的; p.communicate()p.wait() 不是那样工作的。


如果通过 ssh 运行,这会稍微改变:

import pipes # in Python 2.x; in 3.x, use shlex.quote() instead
p = subprocess.Popen(['ssh', ' '.join(
[pipes.quote(s) for s in ['unrar', 'e', '%s/%s' % (root, i), testfolder]])

关于python等待shell命令完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16196712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com