Dan.P
Dan.P

Reputation: 53

Calling Python package from command line / PyCharm

I am creating a Python package, I anticipate that it will be called both by command line and from other scripts. Here is a simplified version of my file structure:

GREProject/
    __init__.py
    __main__.py
    Parsing.py

Parseing.py contains a method, parse(), it takes two arguments, an input file and an output file. I am trying to figure out the proper code for "__main__.py" so that when the following is called from the command line or terminal the arguments will be passed to "parse()":

Python GREProject -i input.file -o output.file

I have tried this numerous ways but they have all met with failure, I do believe I need the "-m" flag for the interpreter but more than that I don't know. Example with the flag:

Python -m GREProject -i input.file -o output.file

When running the later command I receive the following error:

Import by filename is not supported.

Presumably from this line:

from . import Parsing

Upvotes: 2

Views: 580

Answers (1)

Dan.P
Dan.P

Reputation: 53

Ok, turns out this was a problem with my IDE, PyCharm. No idea why I recieved this error but I have setting that fixed it:

Import by filename is not supported.

For the record here are the options I set in my Pycharm project

Script:
    GREProject
Script parameters:
    -i .\GREProject\pr2.nyc1 -o .\GREProject\Test.pkl
Enviroment variables:
    PYTHONUNBUFFERED=1
Python interpreter:
    Python 2.7.11 (c:\Python27\python.exe)
Interpreter options:
    -m
Working directory:
    C:\Users\probert.dan\PycharmProjects

Here is an explanation of the options:

  • Script: This is the script to run, by default PyCharm will only insert absolute references to .py files, nothing prevents you from manually typing in a relative reference, in this case it is the GREProjects folder.
  • Script Parameters: These are passed onto the script itself, in this case I am telling my script that the input file is ".\GREProject\pr2.nyc1" which means, look the file "pr2.nyc1" in the "GREProject" directory below the current working directory.
  • Environment variables: This was set by PyCharm and left unchanged.
  • Python interpreter: My active interpreter.
  • Interpreter options: The option here tells python that we are calling a module, python then knows to access the "__main__.py" file.
  • Working directory: The directory the script is run from, I chose the directory above "GREProject"

For reference here is the contents of my "__main__.py file":

from . import Parsing
import argparse

parser = argparse.ArgumentParser(description='Parse flags.')
parser.add_argument('-i', help='Import file.')
parser.add_argument('-o', help='(Optional) Output file.')
arguments = parser.parse_args()
Parsing.parse(arguments.i, arguments.o)

It is also important to note that debugging in PyCharm is not possible like this. Here is the solution to debugging: Intellij/Pycharm can't debug Python modules

Upvotes: 1

Related Questions