【问题标题】:how to run bash inside python loop [duplicate]如何在python循环中运行bash [重复]
【发布时间】:2021-06-07 11:33:18
【问题描述】:

我有两个文件如下,我想循环这两个文件以根据每个文件中的行创建不同的组合,然后将它们作为ij 输入到 python 中的 bash 脚本:

文件1

aaaa
tttt
cccc
gggg

文件2

gggg
tttt
aaaa
cccc
ssss

我想循环播放这两个文件,然后将它们输入到bash 脚本。所以ij 的每个组合都应该是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

【问题讨论】:

  • 使用 os.system() 或 subprocess.call() 执行

标签: python bash loops parsing


【解决方案1】:

您可以使用subprocess.run()subprocess.check_output() 取决于您是需要简单地运行脚本,还是希望在 Python 中返回输出。

这是一个愚蠢的例子

bash_example.sh

echo 'Hello from Bash'

从python内部:

from subprocess import check_output

check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'

【讨论】:

  • 如果您仍然明确地运行 Bash,shell=True 非常愚蠢(您正在创建 三个 shell 来执行 一个 echo)。可能会尝试check_output(['bash', 'bash_example.sh']),当然如果 Bash 脚本可以正确执行,您可以只使用check_output(['bash_example.sh'])。 OP 可能更感兴趣的是如何将 Python 变量作为参数传递给脚本,但这显然是一个常见的重复。
  • @tripleee 你是对的。我经常使用shell=True 来避免将列表而不是字符串传递给check_outputrun
猜你喜欢
  • 2018-02-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2016-09-07
  • 2021-03-23
  • 2014-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多