Uladz Kha
Uladz Kha

Reputation: 2354

How to get variable with directory path in python script from bash script?

I would like to know how can i get current working directory as parameter in python script, my bash script looks like:

#!/bin/bash
working_derictory=($PWD) #set working directory to variable
eval "python3.8 main.py" working_directory

in python script i try to get this variable using:

import sys
print (sys.argv[1])

after execution i get working_directory text instead of directory path also i tried to change it eval "python3.8 main.py" working_directory to eval "python3.8 main.py" pwd but i got the same result. Please point me what i did wrong ?

Upvotes: 1

Views: 2234

Answers (2)

Alfe
Alfe

Reputation: 59426

You have several options.

working_directory=$PWD
python3.8 main.py "$working_directory"

This will pass the value of your variable as a command line argument. In Python you will use sys.argv[1] to access it.

export working_directory=$PWD
python3.8 main.py

This will add an environment variable using export. In Python you can access this using import os and os.getenv('working_directory').

You also can use this syntax:

working_directory=$PWD python3.8 main.py

This results in the same (an environment variable) without cluttering the environment of the calling shell.

Upvotes: 2

vlemaistre
vlemaistre

Reputation: 3331

You can use the pathlib library to avoid putting it as a parameter:

import pathlib

working_derictory = pathlib.Path().absolute()

Upvotes: 1

Related Questions