用python文件传递参数并将其存储为变量

用python文件传递参数并将其存储为变量,python,Python,运行pythonfile时,我需要传递一些参数 参数是一个路径,/home/user/,它应该存储在该路径的列表中,以便以后在代码中使用 示例:运行文件时。findfiles.py/home/user//home/user2/ 我想将列表传递到glob.glob('path*.txt'),以便它可以搜索以.txt结尾的文件 这就是我现在得到的: import glob test = glob.glob('*.txt') text1 = "file " text2 = " has followi

运行pythonfile时,我需要传递一些参数

参数是一个路径,
/home/user/
,它应该存储在该路径的列表中,以便以后在代码中使用

示例:运行文件时。findfiles.py/home/user//home/user2/

我想将列表传递到
glob.glob('path*.txt')
,以便它可以搜索以.txt结尾的文件

这就是我现在得到的:

import glob

test = glob.glob('*.txt')
text1 = "file "
text2 = " has following 2 line inside"
for files in test:
        print text1 + files + text2 
        f = open(files, "r")
        print(f.readline())
        print(f.readline())

它在当前目录中*.txt之后搜索,并列出文件和前两行。

您有几个选项:

1.使用
Argparse
,阅读更多信息:

2.使用
sys.argv
,在您的简单案例中,它似乎是最简单的:

import sys
script_argument = sys.argv[1:]
print script_argument 
# output is : "['/home/user/', '/home/user2/']" 

根据你的需要使用它。

Thx的提示,但我最后使用的是

printfiles.py/home/user//home/user2/ 这两个参数将存储在列表中

import glob, sys, os
list = []
list = sys.argv
    for stuff in list:
    result = glob.glob(os.path.join(stuff, '*.txt'))
    print stuff
将返回找到的.txt文件。 我可以稍后打开它们并给出结果

for files in result:
                        print text1 + files + text2 
                        f = open(files, "r")
                        print(f.readline())

那么你的问题到底是什么?我不清楚你在问什么看看标准库中的模块
argparse