Python Forum
Call a bash script from within a Python programme
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Call a bash script from within a Python programme
#1
I have a lot of students. I keep all their results in an Excel file.

As the term goes on, this Excel file gets more and more columns.

Some students want to see their scores, so I made a little programme to create individual, 1-page Excel files for each student.

Then I have a bash script lp_XL.sh which converts the Excel files to PDF, then sends them to the printer.

I would like to call the bash script from within the Python code which makes the individual Excel files, just to do everything in 1 fell swoop!

How can I do that?
Reply
#2
you can read excel files directly in python.
There are several packages available for this.

The easiest in Pandas see: https://pandas.pydata.org/docs/reference...excel.html

and then select the data you wish to save to PDF.

There are many examples available to do this, but they are simple
google 'convert pandas dataframe to PDF' to see some possibilities
Pedroski55 likes this post
Reply
#3
If you already have a script for this you can do
import subprocess as sp
sp.run(['lp_XL.sh', 'foo.xls'])
If you have libreoffice installed, it can also be done by calling the 'soffice' command with appropriate arguments.
Pedroski55 likes this post
Reply
#4
Thank you both!

I haven't used pandas much, so I am not familiar with it.

I can handle openpyxl and usually get what I want.

subprocess is what I was thinking of, I knew I had heard of a module to do this, but I couldn't remember the name and I have never used it!

I added this to bottom of my Python, works great! (Have to pass the name of the course as a parameter.)

print('Now sending the files to the printer ... ')     
sp.run(['/home/pedro/myBashscripts/lp_XL.sh', course])
I use this in bash to convert XL to PDF ($1 is the first parameter passed to the bash script, I only have 1 parameter):

Quote:XLfiles="/home/pedro/winter2021/$1/individual_stats/*.xlsx"
outPut="/home/pedro/winter2021/$1/individual_stats/"
for X in $XLfiles;
do
echo "This is one of the files:"
printf $X;
echo "\n";
echo "Now converting the file to PDF ... "
libreoffice --headless --convert-to pdf --outdir $outPut $X;
done

and this to send to the printer:
Quote:PDFfiles="/home/pedro/winter2021/$1/individual_stats/*.pdf" # local machine
# batch print PDF files

for X in $PDFfiles;
do
echo "This is one of the files:"
printf $X;
echo "Now sending the file to the printer ... "
lp -d "EPSON-L380-Series" $X;
done
Reply
#5
You can do everything with Python:

import calendar
import datetime
import subprocess

from pathlib import Path


def get_season(date: datetime.date) -> str:
    year = date.year
    leap = calendar.isleap(year)
    
    if datetime.date(year, 3, 1) <= date <= datetime.date(year, 5, 31):
        return f"Spring{year}"
    elif datetime.date(year, 6, 1) <= date <= datetime.date(year, 8, 31):
        return f"Summer{year}"
    elif datetime.date(year, 9, 1) <= date <= datetime.date(year, 11, 30):
        return f"Autum{year}"
    elif datetime.date(year, 12, 1) <= date <= datetime.date(year, 12, 31):
        return f"Winter{year}"
    elif datetime.date(year, 1, 1) <= date <= datetime.date(year, 2, 28 + leap):
        return f"Winter{year}"
    else:
        raise ValueError("Sorry, I made a mistake")


def to_pdf(root_path: str, date: datetime.date, i) -> None:
    season = get_season(date)
    root_path = Path(root_path, season, str(i), "individual_stats")
    print(f"Processing {root_path}")
    cmd = ["localc", "--headless", "--convert-to", "pdf", "--outdir"]
    for file in root_path.glob("*.xlsx"):
        if not file.is_file():
            continue
        
        if (pdf_file := file.with_suffix(".pdf")).exists():
            print(f"File {pdf_file} exists, skipping")
            continue
            
        print(f"Converting {file}")
        task = [*cmd, root_path, file]
        run(task)


def run(cmd):
    proc = subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)    
    if proc.returncode != 0:
        print(proc.returncode)
        print(f"Failed to convert {cmd[-1]}")
Test:
print(get_season(datetime.date.today()))
Output:
Winter2021
print(get_season(datetime.date(2020, 2, 29)))
Output:
Winter2020
to_pdf("/home/deadeye/", datetime.date.today(), "foo")
Output:
Processing /home/deadeye/Winter2021/foo/individual_stats Converting /home/deadeye/Winter2021/foo/individual_stats/1.xlsx Converting /home/deadeye/Winter2021/foo/individual_stats/5.xlsx Converting /home/deadeye/Winter2021/foo/individual_stats/Unbenannt 1.xlsx Converting /home/deadeye/Winter2021/foo/individual_stats/4.xlsx Converting /home/deadeye/Winter2021/foo/individual_stats/2.xlsx Converting /home/deadeye/Winter2021/foo/individual_stats/3.xlsx
Pedroski55 likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Thank you very much!

Duly copied and saved for later analysis!

Quote:You can do everything with Python:

Not quite. I wrote a programme to give me the winning lottery numbers.

I haven't won yet. Maybe a programming error??
Reply
#7
(Dec-05-2021, 10:24 PM)Pedroski55 Wrote: I haven't won yet. Maybe a programming error??

I've learned from politics. Buying all parties together, increases the chance to win to 100%.
This is cheaper than paying for all possible lottery numbers and doing it, will give a negative outcome.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is possible to run the python command to call python script on linux? cuten222 6 634 Jan-30-2024, 09:05 PM
Last Post: DeaD_EyE
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,009 Jun-29-2023, 11:57 AM
Last Post: gologica
  math formula does not give the same result as bash script [SOLVED] AlphaInc 3 921 Apr-02-2023, 07:21 PM
Last Post: AlphaInc
  Showing and saving the output of a python file run through bash Rim 3 2,371 Oct-06-2021, 10:48 AM
Last Post: gerpark
  Automatic user/password entry on prompt by bash script PBOX_XS4_2001 3 2,727 May-18-2021, 06:42 PM
Last Post: Skaperen
  Programme will not returns the day number not the day name Oldman45 8 2,981 Jul-27-2020, 11:29 AM
Last Post: Oldman45
  How to kill a bash script running as root from a python script? jc_lafleur 4 5,791 Jun-26-2020, 10:50 PM
Last Post: jc_lafleur
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,248 May-28-2020, 05:27 PM
Last Post: micseydel
  Call pip3 from python folder build by me call pip3 from the /usr/bin Suryavarman 3 3,628 Oct-07-2019, 10:23 PM
Last Post: Suryavarman
  Using VBA to Call a Python script causes error in pyodbc connector pcarra 1 2,775 Jun-11-2019, 04:14 PM
Last Post: pcarra

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020