简体   繁体   中英

Run python from bash script that is run by another bash script

I currently have a folder structure that will contain a few python scripts which need to be fired from a certain folder but I would like to write a global script that runs each python script via a seperate script in each folder.

-Obtainer
--Persona
---Arthur
----start.sh
--Initialise.sh

-Persona
--Arthur
---lib
----pybot
-----pybot.py

When I run initialise I am aiming to make initialise run "start.sh" Arthur is the bot and there will be more folders with different names and initialise with find and fire each start.sh.

In initialise.sh I have:

#!/bin/bash
. ./Persona/Arthur/start.sh

In start.sh I have:

#!/bin/bash
python ../../../Persona/Arthur/lib/pybot/pybot.py

I get this error:

python: can't open file '../../../Persona/Arthur/lib/pybot/pybot.py': [Errno 2] No such file or directory

However if I run the start.sh itself from its directory it runs fine. This is because I assume it's running it from the proper shell and consequently directory. Is there a way to make the main script run the start.sh in it's own shell like it is being run by itself? The reason why is because the pybot.py saves a bunch of files to where the start script is and because there will be more than one bot I need them to save in each seperate folder.

In the first place, do not source when you mean calling it,

#!/bin/bash
. ./Persona/Arthur/start.sh

Don't do this.

Your script has a number of issue. It won't work because of your current working directory is uncertain. You'd better have your script derive the path to relieve yourself from the hustle of abs paths or relative paths.

The general code could be

script_dir=`dirname "${BASH_SOURCE[0]}"`

then you can use this to derive the path of your target file,

#!/bin/bash
script_dir=`dirname "${BASH_SOURCE[0]}"`
"$script_dir/Persona/Arthur/start.sh"

Your python invocation becomes:

#!/bin/bash
script_dir=`dirname "${BASH_SOURCE[0]}"`
python "$script_dir/../../../Persona/Arthur/lib/pybot/pybot.py"

This should work out properly.

Regarding BASH_SOURCE , check out https://www.gnu.org/software/bash/manual/html_node/Bash-Variables.html


If you want the directory of start.sh to be cwd, you should call cd :

#!/bin/bash
script_dir=`dirname "${BASH_SOURCE[0]}"`
cd "$script_dir"
python "$script_dir/../../../Persona/Arthur/lib/pybot/pybot.py"

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