PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to set environment variable for my user from cronjob in debian linux?

 August 21, 2022     cron, environment-variables, python     No comments   

Issue

I was trying to set environment variable from my cronjob. Apparently crontab is running on different shell than normal scripts when i run them on my user.

This is my crontab:

* * * * * /home/jan_necinski_binance/miniconda3/bin/python gethistoricals.py >> output.txt

and this is my file that is running in crontab:

import pandas as pd
from binance.client import Client
import os

client = Client(os.getenv('API_KEY'), os.getenv('API_SECRET'))

def GetHistoricalData(symbol: str, ST: int, LT: int, interval: str, to: str):
    df = pd.DataFrame(client.get_historical_klines(symbol, interval, str(LT) + ' days ago UTC', to))
    closes = pd.DataFrame(df[4])
    closes.columns = ['Close']
    closes['ST'] = closes.Close.rolling(ST - 1).sum()
    closes['LT'] = closes.Close.rolling(LT - 1).sum()
    closes.dropna(inplace=True)
    return closes

def HistST(hist):
    histST = str(hist['ST'].values[0])
    return histST

def HistLT(hist):
    histLT = str(hist['LT'].values[0])
    return histLT

os.environ['ST'] = HistST(GetHistoricalData('ATOMUSDT', 7, 25, '1d', '1 day ago UTC'))
os.environ['LT'] = HistLT(GetHistoricalData('ATOMUSDT', 7, 25, '1d', '1 day ago UTC'))

print(os.getenv('ST'))
print('cronjob works correctly')

So to sum up my problem is that crontab sets environment variable in different enviroment so my scripts cannot acces them. Please help!!!


Solution

The cron subsystem does not set environment variables. I'll bet you're setting those env vars in your ~/.bashrc. That startup script is not read by non-interactive shells such as those launched by cron. The easiest way to deal with this is to put your env vars in a separate script (I like to name it ~/.environ) then source that file in your ~/.bashrc and your cron job. For example:

* * * * * source ~/.environ; /home/jan_necinski_binance/miniconda3/bin/python gethistoricals.py >> output.txt


Answered By - Kurtis Rader
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing