0

I am using one shell script to call python function -

python -c 'import create_table; create_table.createTable()'

This script is in "scripts" directory and create_table.py file is in another directory - "cdk" Folder structure will look like this -

infra -> cdk -> create_table.py
      -> scripts -> run-script.sh

cdk and scripts directories are at same level inside infra directory.

When I am trying to run my script it is giving below error -

ModuleNotFoundError: No module named 'create_table'

I tried placing create_table.py file in scripts directory, but still it's giving same error. I am referring this question - Calling a Python function from a shell script Can anyone please help me out? Am I missing something here?

Update - create_table.py code

import boto3

def createTable():
    print("createTable function")

There is no class in this python file.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Nitesh
  • 1,477
  • 5
  • 23
  • 34

3 Answers3

0

Your script and package are in different directories. You need to add __init__.py to your cdk. This will tell python it's a module. Then run python -c 'import ..cdk.create_table; create_table.createTable()

k.avinash
  • 81
  • 7
  • Do I need to add anything in __init__.py file? And do I need to add two dots before cdk.create_table – Nitesh Nov 19 '19 at 08:48
  • `__init.py__` is a empty file indicating directory will acts as module. You have to give relative or absolute path. Add .. while importing indicates it has to get out from scripts and go to cdk – k.avinash Nov 20 '19 at 09:17
0

Import the module in a correct way

also use createTable() directly NOT create_table.createTable()

python -c 'import sys; sys.path.insert(0, "../cdk"); from create_table import createTable; createTable()'
Ahmed Abdelazim
  • 717
  • 7
  • 14
0

Most likely you're running into problems because imports depend on the path from which you're calling the run-script.sh. A solution to this might be adding:

if __name__ == "__main__":
    createTable()

at the end of create_table.py and replacing the content of run-script.sh with:

#!/bin/bash
pth=`dirname $0`
python3 $pth/../cdk/create_table.py

After doing so you should be able run it from any path you want/need to.

machnic
  • 2,304
  • 2
  • 17
  • 21