Home > database >  Passing a variable as flag value to a python script
Passing a variable as flag value to a python script

Time:02-16

I am very novice using Python.

I would like to know how I can use a variable as a flag when calling a python script from inside a jupyter notebook or another python script.

Example: inside a jupyter notebook, I have the following command:

! python my_test.py --directory ~/my_data/current_data/2022/february

I would like to place that long directory path in a variable like this:

mydata = r"~/my_data/current_data/2022/february"

and then call the script

! python my_test.py --directory mydata

The interpreter replies that "mydata" is not a directory, which means for me that it is taking "mydata" as a value and not as the name of a variable containing the value.

This is extremely important as I am running in a Windows environment where paths are usually long as with blanks in the middle, like this:

C:\Users\jtorr\Documents\Open Classrooms\Project 7 - Proof of concept\cac40_data

Thanks for your help.

Johnny

CodePudding user response:

You are using the ipython interactive kernel in Jupyter. Its documentation includes a section System Shell Commands. Specifically

To pass the values of Python variables or expressions to system commands, prefix them with $

The command to use is

! python my_test.py --directory $mydata

CodePudding user response:

The (unsafe) way to do this would be to use the eval() function which can handle anonymous Python expressions, like variable names, though this is not recommended for serious security reasons, as it allows any expression to be run and executed, including malicious code.

You can do this with: eval(arg) to resolve the command line argument arg to its actual value and return the file path.

The better way of doing this would be to store the mydata variable in a dictionary like so:

paths = {
    mydata: r"~/my_data/current_data/2022/february"
}

Then, you can simply do paths[arg] and use key notation to get the corresponding variable from the paths dictionary and retrieve the file path. This has the added benefit of not allowing a malicious actor to inject code into your application.

  • Related