1

I have a python script which takes various options from the command line

e.g.

-runs with gui

python myscript.py -gui

-runs without requiring user prompts

python myscript.py -aut

-runs with input data taken from input.py

python myscript.py input.py

-and combinations of the above e.g. runs automatically taking input from input.py

python myscript.py -aut input.py

I would like to be able to call this from anywhere on my linux box. How can I do this? I have tried aliasing this in my .bashrc file, but using this method it is unable to accept any of the input options. I have also tried

export PATH=$PATH:/path/to/folder/above_myscript/

but this only recognises the command if I type myscript, not python myscript . Typing just myscript obviously is unable to run the python script.

I have also tried writing a shell script which I could call.

#!/bin/bash
#file: myscript.sh

python '/path/to/folder/above_myscript/myscript.py'

However, again I am also unable to pass any options to it. What is the best solution to this problem?

2 Answers 2

4

If you add #!/usr/bin/env python to the top of your myscript.py file and run chmod +x myscript.py on it you should be able to run myscript.py without needing to put python before it. This should let you use the PATH changing method you had before.

Sign up to request clarification or add additional context in comments.

4 Comments

This nearly works for me. However, within myscript.py I have a subprocess command which calls myscript_gui.py, which then calls some image files. myscript.py can't find myscript_gui.py unless I explicitly include the path to this file and myscript_gui.py can't find the image files either. Is there a way for python to use what's already on my linux path to run the gui?
@218 stackoverflow.com/a/246128/3447365 This answer shows you how to get the directory of the script you are calling. If the myscript_gui.py script is in the same directory, which i'm assuming it is? Then you can prepend the directory path to where you call it and it should work :)
I'm afraid I don't understand how to do that - the link is for bash script which python can't read so DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) just returns SyntaxError: invalid syntax
@218 Sorry I must have derped big time, was answering a bash question a the time also :) In python you can use os.path.dirname(os.path.realpath(__file__)) to get the directory that the script is in. You can then attach this to the start of your myscript_gui.py script to get the location of it :)
0

try this :

python /path/to/folder/above_myscript/myscript.py

or this :

cd /path/to/folder/above_myscript && python myscript.py

on your shell script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.