Python 如何为txt文件中的每一行执行命令

Python 如何为txt文件中的每一行执行命令,python,linux,Python,Linux,我正在尝试自动研究我拥有的一个域列表。这个列表是一个.txt文件,大约350/400行。 我需要为txt文件中的每一行提供使用py脚本的相同命令。诸如此类: import os with open('/home/dogher/Desktop/copia.txt') as f: for line in f: process(line) os.system("/home/dogher/Desktop/theHarvester-master/theHarves

我正在尝试自动研究我拥有的一个域列表。这个列表是一个.txt文件,大约350/400行。 我需要为txt文件中的每一行提供使用py脚本的相同命令。诸如此类:

import os

with open('/home/dogher/Desktop/copia.txt') as f:
    for line in f:
        process(line)
        os.system("/home/dogher/Desktop/theHarvester-master/theHarvester.py -d "(line)" -l 300 -b google -f "(line)".html") 
我知道os.system有错误的语法,但我不知道如何在命令行中插入文本。。 非常感谢,很抱歉英语不好

import os
with open('data.txt') as f:
for line in f:
    os.system('python other.py ' + line)
如果other.py的内容如下:

import sys
print sys.argv[1]
然后,第一个代码段的输出将是data.txt的内容。
我希望这是您想要的,而不是简单地打印,您也可以处理您的行。

您的方法使文件的每一行都接受shell的评估,如果遇到一行包含对shell有特殊意义的字符:空格、引号、圆括号、符号、分号,等。即使今天的输入文件不包含任何这样的字符,您的下一个项目也会。因此,今天就要学会正确地做到这一点:

for line in openfile:
    subprocess.call("/home/dogher/Desktop/theHarvester-master/theHarvester.py", 
         "-d", line, "-l", "300", "-b", "google", "-f", line+".html")

由于不需要解析命令行参数,因此子流程将在不涉及shell的情况下执行您的命令。

由于Linux标记,我建议您使用bash执行所需的操作

process_file.sh:

#!/bin/bash

#your input file
input=my_file.txt

#your python script
py_script=script.py

# use each line of the file `input` as argument of your script     
while read line
do
  python $py_script $line
done < "$input"

希望以下解决方案对您有所帮助:

with open('name.txt') as fp:
    for line in fp:
        subprocess.check_output('python name.py {}'.format(line), shell=True)
我使用过的示例文件:

name.py

import sys
name = sys.argv[1] 
print name
name.txt:

harry
kat
patrick

您能给出一个文件示例吗?使用子流程模块。使用调用方法而不是操作系统
harry
kat
patrick