简体   繁体   中英

How do I run my pycharm file in the command line using arguments from the user?

I have created a fileSearch program in pycharm and I would like to run it in my command line using arguments from the user.

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

I would like to run this in the command line using user inputs like:

C:\..\..> fileSearch.py --fileName --Directory

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

You can use argparse for command input parameter parser with option. you can also use sys.arv . For more details you can go through 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

command line example:

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

For command line apps I like to use the Click package http://click.pocoo.org/5/

in your case it would be something like so.

# 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()

Then from the command line you can run

$ python app.py -f file.txt -d dirname
$ python app.py --filename=file.txt --directory=dirname
$ python app.py --help // prints your help text

Click has a ton of great features to build out robust CLI apps. Like I said it is my goto.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM