Writing a command line app - python

I am in Ubuntu 16.4. I have just written a program that can be executed using the command(assuming i'm in the correct directory) ./Main.py -h
However I want this to be distributable, so that you can use it from the command line like nmap or youtube-dl. My idea was to put an alias is .bashrc. This had two problems. One was that I couldn't have the options(-h) in the command if there was a command after it, so it changed your directory. Second I don't know what directory the users would install it in. So even if I appended the alias to .bashrc I wouldn't know what directory it was installed in. I tried to fix this issue by copying the files to their home directory but this gave me an error that said Permission Denied(while running the program) as it needs to be able to write to files. I tryed for a while to fix this but in the end they needed to run it as root and that shouldn't be necessary. So how should I install this so that it can be used like a regular command line tool?

Normal convention for command line programs is to place them on the default path, which is to say in one of the directories represented by the $PATH environment variable. There is also a default on various systems.
This way, when you enter a command, your shell will attempt to find a match in one of these directories, and you can omit the ./ part of the invocation.
Try the command echo $PATH to see what the path directories are on your particular system. /usr/local/bin is usually a good choice for a custom script.
Since you are using Python, you will also want to set it up as an executable script, which is a pretty common thing to do.
Good luck!

Related

Conda: Command not found

I'm a 17-year-old, and I am new to programming. I installed anaconda and python on my laptop however every time that I run code in Sublime Text it gives this error before printing whatever I want it to print:
/Users/eyan/.bash_profile: line 20: conda: command not found
It's really annoying so is there a way to get rid of it.
The difference between bash and zshell are minimal. They are both a "shell" that run in the terminal. A shell is what allows you to run commands in the terminal. It has its own language called bash or alternatively shell scripting. If you have ever typed ls or cd in a terminal, you are using bash commands to move around or look at things in the terminal. (The terminal itself is just the little oftentimes black square you type into.) It doesn't really matter which one you pick at this point, but you should just go with one.
If you pick bash, the files that interact with it will be under your home directory, the error tells you exactly where. /Users/eyan/.bash_profile the .bash_profile sets some configurations for bash.
If you pick zshell, the files will instead of starting with '.bash_ they'll start with .zsh the most common one will be .zshrc and it will be in the same home directory. So /Users/eyan/.zshrc will be the config file for zshell.
Pick one and just stay with it for now.
In either case, you want to initialize conda.
In your terminal, if you type:
which conda
It should tell you where your conda is installed. If you get a bunch of nonsense running that, try which python. One of them should give you something like this output:
/Users/eyan/opt/anaconda3/bin/python
Change the python in that line to activate and add the command source to the front. So type:
source /Users/eyan/opt/anaconda3/bin/activate
Once you've done that type:
conda init
All of this is done in the terminal. And that should add a bunch of stuff to your shell profiles. (That's those files in your home directory like .bash and .zshrc.)
If you close and reopen your terminal or type EXEC $SHELL in the same terminal window, you should be able to use conda.
You can also see what was added to your bash (or zsh) profiles by typing:
cat /Users/eyan/.bash_profile
(Or if you've chosen zshell, run cat /Users/eyan/.zshrc)
You'll see that conda added quite a few lines to it. Don't worry about what those lines do for now, but you can see them there.
That means that your shell doesn't know where to find conda binary. In order for him to know where to look for it you should run:
/absolute/path/to/anaconda3/folder/bin/conda init
source ~/.bash_profile
usually the default path should be ~/anaconda3 and therefore you should be good with
~/anaconda3/bin/conda init
source ~/.bash_profile

How to run a python script through command line? [duplicate]

This question already has an answer here:
How is git able to run C scripts in the current directory as a command on terminal?
(1 answer)
Closed 4 years ago.
I have been looking into bash and shell and have been trying to figure out how Git is able to run its C script in any directory. I have recently fiddled with environment variables, although this just redirects you to run a script in the location of that file, plus you have the $. How is Git able to integrate its scripts into the terminal? How would I be able to do the same with an arbitrary script in python?
It is really hard to find any information without knowing the correct terminology although here's my attempt of mimicking such a command line system as git.
I start with a command file in a folder in my home directory
something.command
Which on the inside directs me to a python script. e.g
cd
cd python_script_location
python3 script.py
Then I make this an environment variable through editing the .bash_profile.
export pyinit=/Users/Charlkie/vcscmd/pyinit.command
This although will just run a script in another directory. How can I make a terminal command that runs a python script in the current directory? Any help would be greatly appreciated :)
There is no requirement for scripts to switch working directories.
In fact, well-written scripts should, as a rule, not need to switch directories at all.
If the script requires access to a configuration file or something, a common set of arrangements is to allow the user to configure the file's location via an environment variable, then fall back to a system-wide standard location, and then fall back to the current directory, and as a last resort, perhaps examine the script's location via argv[0] (which is $0 in shell scripts).
In concrete terms, something.command should probably look like
exec python3 $HOME/python_script_location/script.py "$#"
... in which case you might as well make $HOME/python_script_location/script.py executable with a proper shebang (in this case usually #!/usr/bin/env python3) and maybe ln -s $HOME/python_script_location/script.py $HOME/bin (assuming $HOME/bin is already on your PATH) or maybe alias something.command=$HOME/python_script_location/script.py if you only need it interactively and don't otherwise have a directory in your PATH for your own personal scripts.
Add a symlink /usr/bin pointing at your script. Check this question how to do it: How to symlink a file in Linux?
Use which command to validate if the system can see it.

bash: 'command not found' for python, r and nano

On git bash, I receive a command not found message for python, r and nano.
I am on Windows 10. I do not know what I am doing wrong.
I type
r --version
python --version
nano --version
and they all return command not found.
I read something that had me try
alias python='winpty python.exe'
and it renamed python, but when I tried
touch .bashrc
it returned
touch: command not found
I followed the instructions in a Github course, PS239T. I have been fortunate, except for getting these three programs to work.
I tried
build/console.exe c:/Python36/python.exe
and it returned
build/console.exe: No such file or directory
I tried
PATH=$PATH:/c/Python36/
$ export PATH="$PATH:/c/Python36"
echo 'export PATH="$PATH:/c/Python36"' > .profile
and nothing.
I got Python 64-bit via Anaconda.
I tried setting up the Python 3.4 environment
conda create –n py34 python=3.4 anaconda
./python name_of_your_python_script.py
nothing.
which python
got me a huge directory path:
which: no python in (/c/Users/Edward/bin:/mingw64/bin:/usr/local/bin:usr
/bin:/bin:/mingw64/bin:/usr/bin:c/user/Edward/bin:/c/Program Files
(X86)/Intel/ 1CLS client:/c/Program Files/Intel/1CLS Client:/c/Windows
/System32:/C/Windows:/C/Windows/Sytem32/Wbem:/c/Windows/System32
WindowsPowerShell/V1.0:/c/Program Files/Intel/Intel(R) Management Engine
Components/Dal:/c/Program Files/Intel/Intel(R) Management Engine
Components/IPT:/c/Program Files (x86)/Intel/Intel(R) magament Engine
Components/IPT:/c/Program Files (X86)/Intel/Intel(R) Management Engine
Components/IPT:/c/WINDOWS/Syste,32/Wbem:/c/WINDOWS/System32
/WindowsPowerShell/v1.0:/c/Program Files (x86)/Rand McNally/RNDDock
/GtkSharp/2.12/bin/:/c/Program Files d/AppData/Local/Mircosoft
/WindowsApps:/c/Users/Edward/AppData/Local/Pandoc:/usr/bin/vendor_perl:
/usr/bincore_perl:/c/python36
I would have just put up the screenshot or copied and pasted it, but I do not know how.
I am sure I made an error somewhere.
I get the same type of results when I try to figure out what is going on with r and nano.
Update 1
Download and install 'Anaconda'
'https://store.continuum.io/cshop/anaconda/'.
Download the default Python 3 installer 'do not follow the link to version 2'.
Use all of the defaults for installation except make sure to check 'Make Anaconda the default Python.'
Install R by downloading and running
'this .exe file from CRAN'
'http://cran.r-project.org/bin/windows/base/release.htm'.
Also, please install the 'RStudio IDE'
'http://www.rstudio.com/ide/download/desktop'.
All you need is RStudio Desktop.
nano is a basic editor and the default that we use in this class. To install
it, download the Software Carpentry Windows installer
http://files.software-carpentry.org/SWCarpentryInstaller.exe'
and double click on the file to run it. 'This installer requires an active internet connection.'
Sublime Text is a more advanced editor. Download Sublime Text 3 'here'
'https://www.sublimetext.com/3'.
Update 2
I began trying janos advice and ran
/c/Python36/python.exe --version
and it returned
bash: '/c/python36/python.exe: No such file or directory.
I tried to run
PATH="/c/Python36:$PATH" python.exe --version
but it returned
bash: python.exe.: command not found
I tried to run
PATH="/c/Python36:$PATH" python --version
and it returned
bash: python: command not found
Update 3
janos told me I went too far without figuring out the problem, then told me to run
ls -l /c/Python36/python.exe
and it returned
ls: cannot access '/c/Python36/python.exe': no such file or directory.
janos told me to focus on the first error
bash: '/c/python36/python.exe: No such file or directory.
after entering
/c/Python36/python.exe --version
and so there I will focus.
janos asserted
Can you open a file explorer and navigate to C:\Python36, and see python.exe there? Probably not.
and is correct.
I ran
C/Users/Edward/Anaconda3/pkgs/python-3.6.3-h9e2ca53_1/python.exe
with no success.
I ran that in explorer and found that the publisher could not be verified.
Update 4
I went to
'python.org/downloads/release/python-363'
and downloaded 'Windows x86 embeddable zip file' and Unzipped it in
C/Users/Edward/Anaconda3/pkgs
it worked.
Thank you.
I bet I am having the same problems with 'r' and 'nano'.
I am going to run down the list again and perform all the check. I will do the same thing with 'r' and 'nano'.
Everything worked out for Python. I will do 'nano' and 'r' in due course.
I could not find
/c/python36/
so I used
/c/Users/Edward/Anaconda3/pkgs/python-3.6.3-embed-win32/
Update 5
janos is right again. I would need to create the python36 folder as it was not built automatically during the installation. janos' method worked on 'r' and 'subl' or sublime text 3. I gave up on 'nano'.
I found that some of my '.exe' files were in listing with spaces in the names. I moved to the user folder and eliminated any spaces.
I also downloaded version from the official website, and that too helped.
I could not figure out how to get 'nano' to work. I could not even find it on my pc. I used 'subl' instead.
Start from the basics. Try the simplest thing that can possibly work,
and make progress in baby steps,
from one sane state to the next.
The first step is to run a by entering its absolute path directly.
If the Python executable is at /c/Python36/python.exe, then run this:
/c/Python36/python.exe --version
This is very simple and it should just work.
If it doesn't, the command will give you an error message with clues.
A next step could be to simulate adding to PATH. Try this:
PATH="/c/Python36:$PATH" python.exe --version
This is one line. It sets a value to PATH in a way such that it's only active during the execution of the command. After the command completes, the value of PATH will be back to what it was before. This is a good way to test things. Also notice that I prepended to PATH the directory that contains python.exe, not the full path to python.exe.
That's an important point, this is how the PATH variable works.
It's a list of directories, and all executable files in those directories become easily executable by simply typing their name, without having to type their absolute paths.
Next, I would try this:
PATH="/c/Python36:$PATH" python --version
That is, see if you can drop the .exe from the name of the command.
I don't have Windows so I cannot test if this works.
And maybe it doesn't. (But I think it does.)
If everything worked so far, then the next step is to make the PATH setting permanent.
The way to do that is to put the command PATH="/c/Python36:$PATH" into a file that is always executed when you start a new Git Bash session.
If I remember correctly on Windows you can put it in ~/.profile
(a file named .profile in your home directory).
Where is ~? Here's one way to find it:
cd
explorer .
The above opens a file manager inside that directory.
You can use a plain-text editor like Notepad or Wordpad to edit it.
You can also use this shell command to append the line that updates PATH:
echo 'PATH="/c/Python36:$PATH"' >> ~/.profile
This line will get executed in all new Git Bash session.
Not in the current session,
because this file is only executed once.
If everything above worked, then in a new Git Bash session you should be able to run python --version.
If not everything worked, then you need to read the error message you get carefully, and not advance to the next step until the problem is resolved.
It's useless to advance to a next step when you are already not in a sane state.
You can follow the exact same logical process for all the other programs too.

Using Python to generate exports for .bashrc

When I manually build and install projects they are installed into $HOME/.prefix/<project>
Having each project in it's own folder makes it easier to remove later. Right now I have to manually add each project to PATH, LD_LIBRARY_PATH, LIBRARY_PATH, C_INCLUDE, and CPLUS_INCLUDE. I would like to automate this using Python, but I'm running into issues. If I use Python's os.environ then the settings don't persist. I also tried outputting a single command to stdout which is run by .bashrc like this: $(python scan.py). This failed, with the following as an example:
After reloading my .bashrc my PATH variable was literally: $HOME/.prefix/clang/bin:$PATH. The problem is that last $PATH, it should have been expanded to include everything that PATH contained previously.
It sounds like your python script is outputting a string that has $HOME and $PATH in it. bash is not expanding those variables because they are not actually in your bash script.
You could write your python script to get the HOME and PATH environment variables and just output paths, rather than expecting the shell to expand them
You could pass them to your script as command-line arguments
You could eval the output in bash but eval is not necessarily a great habit

How to execute a python command line utility from the terminal in any directory

I have just written a python script to do some batch file operations. I was wondering how i could keep it in some common path like rest of the command line utilities like cd, ls, grep etc.
What i expect is something like this to be done from any directory -
$ script.py arg1 arg2
Just put the script directory into the PATH environment variable, or alternatively put the script in a location that is already in the PATH. On Unix systems, you usually use /home/<nick>/bin for your own scripts and add that to the PATH.
Add the directory it is stored in to your PATH variable? From your prompt, I'm guessing you're using an sh-like shell and from your tags, I'm further assuming OS X. Go into your .bashrc and make the necessary changes.
An alternative approach is to create a python package with entry points and install the program, rather than changing $PATH (using setuptools in setup.py). This has some advantages:
Works outside of shells
Reduces the amount of system-wide configuration, or at least puts it all in side the package.
See Explain Python entry points? and python: simple example for a python egg with a one-file source file? for details.
This has the advantage of keeping all your settings in one place.
You can use the --develop option so that you can still edit your code in place and the --user option to avoid messing python for other users.

Categories

Resources