How to run a Python script connected to the DB file from another directory?
Question:
Downloads
├── pythonScript
├── RANK.db
└── dbCompare.py
I am trying to run a python script which shows all data from a DB table named RANK
.
Above is my directory structure and Downloads
directory is where I want to run the python script.
The python script is located at /Downloads/pythonScript/dbCompare.py
and I am trying to run it from /Downloads
.
In my zsh, I have tried to run it using python pythonScript/dbCompare.py
command from /Downloads
. But it is telling me that there is no RANK
table.
After doing that, I tried to change my working directory to /Downloads/pythonScript
then run it again, using python dbCompare.py
command in zsh.
Then the python script was working.
The reason why I am trying to run this command from /Downloads
is I need to run this command from NodeJS server which is located at /Downloads
.
I have checked my db file if there is a typo or something else but I don’t see any.
How do I run this python script from /Downloads
?
It is only working in /Downloads/pythonScript/
directory.
Answers:
change the path in
sqlite3.connect(‘rank.db’) to sqlite3.connect(‘relative pathrank.db’)
that’s because of at the first connection python will search in the same dir of the script
Check if the db exists before connect()
which will create it if it doesn’t.
db = '/path/to/rank.db'
if not os.path.exists(db):
raise RuntimeError(f'{db} does not exist')
sqlite3.connect(db)
Downloads
├── pythonScript
├── RANK.db
└── dbCompare.py
I am trying to run a python script which shows all data from a DB table named RANK
.
Above is my directory structure and Downloads
directory is where I want to run the python script.
The python script is located at /Downloads/pythonScript/dbCompare.py
and I am trying to run it from /Downloads
.
In my zsh, I have tried to run it using python pythonScript/dbCompare.py
command from /Downloads
. But it is telling me that there is no RANK
table.
After doing that, I tried to change my working directory to /Downloads/pythonScript
then run it again, using python dbCompare.py
command in zsh.
Then the python script was working.
The reason why I am trying to run this command from /Downloads
is I need to run this command from NodeJS server which is located at /Downloads
.
I have checked my db file if there is a typo or something else but I don’t see any.
How do I run this python script from /Downloads
?
It is only working in /Downloads/pythonScript/
directory.
change the path in
sqlite3.connect(‘rank.db’) to sqlite3.connect(‘relative pathrank.db’)
that’s because of at the first connection python will search in the same dir of the script
Check if the db exists before connect()
which will create it if it doesn’t.
db = '/path/to/rank.db'
if not os.path.exists(db):
raise RuntimeError(f'{db} does not exist')
sqlite3.connect(db)