在for循环中使用变量调用Python子进程

克里斯

我试图通过子进程 Popen 函数在 for 循环中传递来调用 bash 脚本。我的意图是,在每次迭代中,从数组out 中提交的新字符串作为参数传递给 Popen 命令。该命令调用一个 bash 脚本,该脚本输出由变量commit标识的文本,并从该特定文本中提取某些行。但是,我无法在 Python for 循环中刷新输出。现在,只有从最终的grepped数据提交被传递到我最后的数据结构(熊猫数据帧)。

accuracy_dictionary = {}
for commit in out:
    accuracy_dictionary.setdefault(commit, {})
    p2 = subprocess.Popen(['~/Desktop/find_accuracies.sh', commit], encoding='utf-8', shell=True, stdout=subprocess.PIPE)
    outputstring = p2.stdout.read()
    # This part below is less critical to the problem at hand
    # I'm putting the data from each file in a dictionary
    for acc_type_line in outputstring.split('\n'):
        accuracy = acc_type_line.split(': ')
        if accuracy != ['']:
            acc_type = accuracy[0]
            value = accuracy[1]
            accuracy_dictionary[commit][acc_type] = float(value)

acc_data = pd.DataFrame.from_dict(accuracy_dictionary).T

这是正在调用的 bash 脚本:

“find_accuracies.sh”:

#!/bin/sh

COMMIT=$1
git show $COMMIT:blahblahfolder/blahblah.txt | grep --line-buffered 'accuracy'

acc_data NROWS = LEN(的数据帧返回)由唯一的填充提交S,但是为每个所有行完全相同的acc_type

例如,我的输出如下所示: 在此处输入图片说明

如何使用 subprocess 命令调用文件“find_accuracies.sh”并让它为每次提交刷新每个文件的唯一值?

翁德雷·K。

我希望这有助于解决您所看到的直接问题:在这里您应该真正使用communicatewith ,subprocess.PIPE因为它等待命令完成并为您提供所有输出:

outputstring = p2.communicate()[0]

您也可以使用方便的方法check_output来达到同样的效果:

outputstring = subprocess.check_output(['~/Desktop/find_accuracies.sh', commit],
                                       encoding='utf-8', shell=True)

或者也在 py3 中使用run也应该这样做:

p2 = subprocess.run(['~/Desktop/find_accuracies.sh', commit],
                    encoding='utf-8', shell=True, stdout=subprocess.PIPE)
outputstring = p2.stdout

现在还有一些评论、提示和建议:

我有点惊讶它对您有用,因为使用shell=True和参数列表应该(请参阅以“On POSIX with shell=True开头的段落)使您commit的底层参数sh围绕您的脚本调用而不是脚本本身。在任何情况下,您都可以(我建议)实际上放弃shell并将HOME解决方案留给python:

from pathlib import Path
executable = Path.home().joinpath('Desktop/find_accuracies.sh')

p2 = subprocess.run([executable, commit],
                    encoding='utf-8', stdout=subprocess.PIPE)
outputstring = p2.stdout

您可以(或必须为 py <3.5)也使用os.path.expanduser('~/Desktop/find_accuracies.sh')代替Path.home()来获取脚本executable另一方面,对于 >=3.7,您可以替换stdout=subprocess.PIPEcapture_output=True.

最后但并非最不重要。这似乎有点不必要的调用bash脚本(尤其双人包裹在sh像原来的例子调用)只运行gitgrep,当我们已经有一个python脚本来处理信息。我实际上会尝试运行相应的git命令,直接获取其大部分输出并在 python 脚本本身中处理其输出以获得感兴趣的位。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章