[英]Calling Python subprocess with variable in for loop
我试图通过子过程Popen函数在for循环中调用bash脚本。 我的意图是,每次迭代都会将数组输出中的新字符串提交作为参数传递给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( out )数据帧,但每个acc_type的所有行的值完全相同
如何使用subprocess命令调用文件“ find_accuracies.sh”,并让其为每次提交刷新每个文件的唯一值?
我希望此帮助能够解决您所遇到的紧迫问题:在这里,您应该真正使用与subprocess.PIPE
communicate
,因为它等待命令完成并提供所有输出:
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
并且参数列表应该起作用(请参阅以“在shell=True
上的POSIX上”开头的段落)使底层sh
commit
参数包裹在脚本调用中,而不是脚本本身。 无论如何,您都可以(并且我建议)实际删除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.PIPE
capture_output=True
替换为capture_output=True
。
最后但并非最不重要。 似乎没有必要调用bash脚本(特别是像原始示例一样,在sh
调用中用double包裹),而当我们已经有了python脚本来处理信息时,只需通过grep
运行git
即可。 实际上,我将尝试直接运行相应的git
命令以获取其大部分输出,并在python脚本本身中处理其输出以获取感兴趣的位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.