如何在python循环中运行bash
我有两个文件,如下所示,我想循环这两个文件,根据每个文件中的行创建不同的组合,然后将它们作为如何在python循环中运行bash,python,bash,loops,parsing,Python,Bash,Loops,Parsing,我有两个文件,如下所示,我想循环这两个文件,根据每个文件中的行创建不同的组合,然后将它们作为I和j输入python中的bash脚本: from subprocess import check_output check_output('bash bash_example.sh', shell=True) b'Hello from Bash\n' 文件1 文件2 我想在这两个文件上循环,然后将它们输入到bash脚本中。因此,i和j的每个组合都应该是bash脚本的输入: f1=[] f2=[] f
I
和j
输入python中的bash脚本:
from subprocess import check_output
check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'
文件1
文件2
我想在这两个文件上循环,然后将它们输入到bash
脚本中。因此,i
和j
的每个组合都应该是bash
脚本的输入:
f1=[]
f2=[]
file1=open('file1.txt','r')
file2=open('file2.txt','r')
for i in file1:
f1.append(i)
for j in file2:
f2.append(j)
for i in f1:
for j in f2:
print(i)
print(j)
bashscript i j
您可以使用或
这取决于您是需要简单地运行脚本,还是希望以Python返回输出
这里有一个愚蠢的例子
bash_示例。sh是
echo 'Hello from Bash'
从python内部:
from subprocess import check_output
check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'
使用os.system()或subprocess.call()执行如果仍然显式运行Bash,
shell=True
非常愚蠢(创建三个shell来执行一个echo
)。可能会尝试检查输出(['bash',bash\u example.sh'])
当然,如果bash脚本可以正确执行,您可以只检查输出(['bash\u example.sh'])
。OP可能更感兴趣的是如何将Python变量作为参数传递给脚本,但这显然是一个常见的重复。@tripleee您是对的。我经常使用shell=True
来避免将列表而不是字符串传递给check\u output
和run
。
from subprocess import check_output
check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'