Search code examples
python-3.xanacondaargvsys

How to set/define/use sys.argv


I'm fairly new to Python, so please bear with me.

Currently, I'm using Python 3.5 in an Anaconda environment on Pycharm, and I am trying to understand how to set/define/use sys.argv so that I can automate several processes before uploading my changes onto github.

For example:

python function/function.py input_folder/input.txt output_folder/output.txt

This means that function.py will take input.txt from input_folder, apply whatever script written in function.py, and store the results into output.txt in folder output_folder.

However, when I type this into terminal, I get the following error:

python: can't open file 'function/function.py': [Errno 2] No such file or directory

Then, typing sys.argv into Python console, I receive the following:

['C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.2\\helpers\\pydev\\pydevconsole.py',
 '53465',
 '53466']

My guess is that if I were to set sys.argv[0:1] correctly, then I should be able to apply function.py to input.txt and store the results into output.txt.

I've already tried to define these directories, but they wouldn't work. Any help would be awesome!


Solution

  • your issue is that python does not know where the function directory exists. If you are trying to run a script from a sub directory like so

    function
    |_function.py
    | 
    input_folder
    |_input.txt 
    |
    |output_folder
    |_output.txt
    

    you must tell python that the function folder is local, so

    python ./function/function.py ./input_folder/input.txt ./output_folder/output.txt
    

    or

    python $PWD/function/function.py $PWD/input_folder/input.txt $PWD/output_folder/output.txt
    

    $PWD is a bash variable that gives the current directory