简体   繁体   中英

How to pass a filepath stored in a variable in one python file to another python file to be read by it?

I want to pass a variable (a file path) grabbed in one python script, to my other python script so that it can read the file and do the necessary calculations. Both python scripts run the way I want them to, they just are not speaking to each other.

The first script is NoShowGUI.py made to browse and grab a csv file's location and store it in booked_file_path :

def open_file():
browse_text.set('Loading...')
booked_file_path = askopenfile(parent=root, mode='rb', title='Choose a file', filetype=[('CSV file', '*.csv')])
if booked_file_path:
    read_csv = (booked_file_path)
    browse_text.set('Loaded')

def run():
    os.system('NoShowCalc.py')
    calculate_text.set("Calculating...")

The second script is NoShowCalc.py , made to read the csv so it can run an analysis on the retrieved booked_file_path :

import pandas as pd

booked = pd.read_csv(booked_file_path, parse_dates=['Appointment Date'])

However, when I try to read the csv in the second py file, I get back NameError: name 'booked_file_path' is not defined .

Now someone told me that to pass a variable between python files, I have to store it in a function in the first file and then call that function in the second python file. From what I have so far it looks like it is stored in a function. I just don't know how to call it in my second py file properly.

I also tried to import my first py file from NoShowCalcGUI.py import open_file but it didn't work and when the GUI popped up, it kept opening up new windows of the gui when I would select my "Calculate" button.

Can anyone help me pass my booked_file_path variable to my second py file so it can do the necessary calculations? Also in a way so the program doesn't keep looping when I select my "Calculate" button too?

Use environmental variables.

import os

# Set environment variables
os.environ['API_USER'] = 'username'
os.environ['API_PASSWORD'] = 'secret'

# Get environment variables
USER = os.getenv('API_USER')
PASSWORD = os.environ.get('API_PASSWORD')

If above doesn't work...Use below

How to Use dotenv Manage Environment Variables

As you increase the number of environment variables you use, you may want to use a library like dotenv to help manage them. It allows you to set or update the environment variables for files in a specific directory by reading them in from another file. This is useful when you delineate different stages of your product by having them in different directories. By using dotenv, you ensure that the environment variables automatically adjust to the environment you have selected by working in that directory. Keep in mind, however, that dotenv is a separate file, and take care not to overlook it when transitioning across systems.

dotenv reads in environment variables from a file named.env. The file should be formatted as follows:

api-token = "abcdef_123456"

#Once that’s created and placed in the same folder as your Python file, environment variables can be called like so:

from dotenv import load_dotenv
load_dotenv()
import os
token = os.environ.get("api-token")

Like many aspects of Python, implementing environment variables isn't cumbersome, provided you have the right tools. By making use of the os package (especially os.environ), along with dotenv when the situation calls for it, you have all the tools you need to begin using environment variables in Python.

Reference: https://www.nylas.com/blog/making-use-of-environment-variables-in-python/

Let's assume you have 2 files, test1.py and test2.py

test1.py:

def my_func():
    FilePath = 'PATH'
    return FilePath

test2.py:

from test6 import my_func

print(my_func())

Here, we import the function my_func from test2.py, and then execute that function (with a return value) and then print it. There are two things you can do: a. Wrap the test1.py in a function that returns the file path, and then import the function b. Wrap the file in a if __name__ == "__main__": loop and use environmental imports

You could pass the csv path as a parameter to the second python script. This approach adds some portability as you can later replace the second script with something else if you need to.

NoShowGUI.py

os.system(f'NoShowCalc.py {booked_file_path}')

NoShowCalc.py

import pandas as pd
import sys

booked = pd.read_csv(sys.argv[1], parse_dates=['Appointment Date'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM