Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python循环中运行bash_Python_Bash_Loops_Parsing - Fatal编程技术网

如何在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'