如何使用用户的参数在命令行中运行pycharm文件?

2024-09-27 07:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pycharm中创建了一个fileSearch程序,我想用用户的参数在命令行中运行它。在

import os
from os.path import join

lookfor = "*insert file name*"

for root, dirs, files in os.walk("*choose directory*"):
print("searching"), root
if lookfor in files:
    print "Found %s" % join(root, lookfor)
    break

我想在命令行中使用以下用户输入运行此命令:

^{pr2}$

Tags: 命令行用户infromimport程序参数os
3条回答

我不确定您是否可以,但您可以编写第一个代码,询问目录,然后从该代码启动其他代码

您可以将argparse用于命令输入参数解析器with option。您也可以使用sys.arv。有关详细信息,请参阅here。在

import os
from os.path import join
# argparse is the python module for user command line parameter parser.
import argparse

# command input from the user with given option
parser = argparse.ArgumentParser()
parser.add_argument('-fileName.', action='store',
                    dest='fileName',
                    help='Give the file Name')
parser.add_argument('-Directory', action='store',
                    dest='dir',
                    help='Give the Directory Name')

# parsing the parameter into results
results = parser.parse_args()

# lookfor = "*insert file name*"

# retrieve the store value from the command line input.
lookfor = results.fileName
dir = results.dir

# for root, dirs, files in os.walk("*choose directory*"):
for root, dirs, files in os.walk(dir):
    print("searching"), root
    if lookfor in files:
        print("Found %s" % join(root, lookfor))
        break

命令行示例:

python fileSearch.py -fileName filename.txt -Directory C:/MyProgram

对于命令行应用程序,我喜欢使用Clickhttp://click.pocoo.org/5/

对你来说应该是这样的。在

# app.py
import click

@click.command()
@click.option('-f', ' filename', help='File name')
@click.option('-d', ' directory', help='Directory')
def run(filename, directory):
    for root, dirs, files in os.walk(directory):
        print('Searching: {}'.format(root))
        if filename in files:
            print "Found %s" % join(root, filename)
            break

if __name__ == '__main__':
    run()

然后从命令行运行

^{pr2}$

Click拥有大量强大的特性来构建健壮的CLI应用程序。就像我说的,这是我的目标。在

相关问题 更多 >

    热门问题