Leveraging the power of bash to execute a python script

I wrote a python script that takes a .txt file as input and produces another .txt file as output. My goal is to create a bash script that I can simply click on from my desktop to run the python script.

This is what I have done so far:

#!/bin/bash
cd /Desktop; 
cd ./py-data;
python ./grab.py;
exit;

However, this just opens up the python script instead of running it in the background and producing the desired output without displaying the python script.

Here is the solution I came up with:

  1. Rename py.bat to py.command

  2. In terminal, execute the following commands:

    $ cd ~/Desktop
    $ chmod 755 py.command

  3. Edit the code using vim and fix any issues like "./configure : /bin/sh^M : bad interpreter":

    :set fileformat=unix

  4. Update the code to:

    #!bin/bash
    cd ~/Desktop
    python search.py
    exit;

Answer №1

To run your script on MacOS, rename the script file with a `.command` extension and ensure it is executable. By double-clicking the file with this specific extension, you will open the Terminal application and any output will be displayed in the terminal window that appears.

=== /Users/john/Desktop/foo.command ===
#!/bin/bash
echo 'hello'

Next:

===  Command prompt===
$ cd ~/Desktop
$ chmod 755 foo.command

Double click on `foo.command` to see a popup window:

Last login: Thu Oct 5
/Users/john/Desktop/foo.command ; exit;
iMac:~/Desktop john$ /Users/john/Desktop/foo.command ; exit;
hello
logout
[Process completed]

The popup window will display various lines, along with your output ("hello").

In your specific case, there are two issues:

First, mentioning `/Desktop` instead of `~/Desktop` may cause the script to fail as the user's Desktop directory is denoted by `~/Desktop`.

Secondly, the output shown in the popup window corresponds to what your script writes directly to standard out. If your script outputs to another file, the information will not display in the popup but rather in the specified file. It varies based on the functionality of your `grab.py` file.

Lastly, stating "run in the background" inaccurately describes the process, as it actually runs in a separate foreground process. I assume that's what you intended to convey.

Answer №2

One potential solution is to adjust the permissions of your bash script using chmod 777, and then delete the file extension. This method may work on macOS, but its compatibility with Linux is uncertain. It could be worth experimenting to see if it resolves the issue.

Answer №3

chmod +x *filename*

To run the command above in your terminal, follow it with these instructions to create a bash file:

cd Desktop/*folder*/
python3 *filename.py*

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traversing a defined axis in Cython

Currently, I am delving into the realm of Cython and have made some modifications to the code found in a tutorial on numerical differentiation: import numpy as np cimport numpy as np import cython np.import_array() def test3(a, int order=2, int axis=-1): ...

Ensure the hex game board contents are displayed correctly

After stumbling upon a hex board game project in Python here, I decided to give it a shot. However, my coding skills are a bit rusty and I'm struggling with creating a function that displays the board contents in the correct format. The desired output ...

Executing Selenium Projects on a Different Computer Using Python

While working on a selenium project involving the Google Drive API and Google Sheets, I encountered an issue when trying to run my project as a .exe file. After converting it with pyinstaller, everything seemed fine. However, when I attempted to transfer ...

Python game where snake refuses to eat food

During code execution, when the snake and food coordinates are identical, the expected behavior is to delete the food item, increase the score by 1, add another square to the snake, and create a new food object. However, the `if` statement in the `next_t ...

Retrieving the current webpage URL without using Selenium

Is there a way to extract an authorization code from an Oauth2 redirect URI without using Selenium Webdriver? When a user clicks "allow" on the Oauth2 consent form, they are redirected back to a specified URL with an important authorization code in the pa ...

Can the request payload be obtained from a POST request in Python?

I am currently working on scraping the names and prices from a particular URL using the requests package. The website I am trying to scrape is . Upon inspecting the site, I noticed that there is a POST request named "items" which contains a payload with an ...

Selecting random elements with multiple loops in NumPy

My goal is to run multiple simulations numerous times in order to achieve a desired simulation distribution. I possess a dataset structured as shown below: fruit_type, reading, prob Apple, 12,.05 apple, 15, .5 orange 18, .99 Below you will find an excer ...

Tips for creating a single plot with multiple dataframes of varying lengths

Seeking Advice on Plotting Multiple Dataframes I am faced with the task of plotting approximately 300 dataframes into a single line chart. The challenge lies in the fact that each dataframe contains a different number of values, which makes aligning them ...

invoke the class that holds the crawling information and parsing function within a separate class

I am a newcomer to scrapy and have a basic question that I can't seem to find an answer to. Here is my code: import os from boto import log from scrapy.utils.project import get_project_settings import scrapy from scrapy.crawler import CrawlerProcess ...

Python's py.test 'HTMLReport' object does not have the 'execute' attribute

How can I include screenshots in my pytest-html report using automated tests? I have made changes to plugin.py: def pytest_runtest_makereport(__multicall__, item): report = __multicall__.execute() extra = getattr(report, 'extra', []) ...

Adding specific key, value pairs to a python dictionary by extracting data from a json file

I am facing an issue where I need to extract a specific key and value from a JSON file in Python and add it to a dictionary. Currently, I have been able to successfully add all the data from the JSON file into my dictionary, but that is not the desired out ...

Tips for avoiding the true/false boolean trap in Python JSON string manipulation

I've got the following code snippet: headers = {'Content-Type': 'application/json', 'cwauth-token': token} payload = {'namePostfix': 'test99682', 'costModel': 'NOT_TRACKED', &apos ...

Verify the compatibility of code with Python versions 3.x

In my Physics course, I am developing a Python script to visualize the progression of a system we are examining. My code is written in Python 3.6 or higher. While sharing my code with classmates during a previous assignment, I encountered an issue. Having ...

"Encountering a Glitch in Google Translate Using Python and

I can't figure out where the issue lies. I followed these sources: https://medium.com/python/python-selenium-mod%C3%BCl%C3%BC-kullan%C4%B1m%C4%B1-ders-1-36983185164c https://www.youtube.com/watch?v=olOswIyeRlY Code from selenium import webdriver from ...

Text written in tags python

My .txt file is semi-structured and has a specific format as shown below: <tags> blabla<text> I want this </text> blabla<text> And this </text> bla<text> ...

Guide to creating radio buttons using a for loop

I have developed a program to determine the number of available voices in a PC, and I plan to implement the use of radiobutton for voice selection. Some PCs may have only one voice while others might have multiple voices. The program is functioning as exp ...

Having issues with the `if elif` statement malfunctioning in Python when using `RandomForestClassifier` from sklearn

I've been working on developing a machine learning program that categorizes user input and determines their preferences. However, I encountered an issue where the if-elif statement always executes the YouTube function, regardless of what the predictiv ...

Parse JSON data, iterate through dictionaries, and convert into markup using Python

I'm working with a JSON file that contains information about different people: { "PersonA": { "Name": "Woman A", "Age": 23, "Info": "Likes cats ..." }, "PersonB": { "Name": "Man B", "Age": 32, ...

Simplifying menu by reducing the clutter and repetitive lines of menu.add_command() statements

Here is an example of what I would like to accomplish, but with more menus and add_command's: editmenu.add_command(label="Cut",state="disabled") editmenu.add_command(label="Copy",state="disabled") editmenu.add_command(label="Paste",state="disabled") ...

Retrieve token and ETH value for an ERC20 transaction using the Etherscan API

I am embarking on my journey with the etherscan API for the first time. My objective is to efficiently extract data from a wallet, specifically focusing on "Token Transfer ERC20", and then be able to calculate the ROI of the wallet. To achieve this, I wil ...