Executing a python script from the terminal in Unix - python

I have a python script and I can't figure how to execute it in the terminal. The script has the #!/usr/bin/python at the beginning, is executable and I've tried locating myself in the right directory and python name.py but what I want to print (ergo what the script says it should print) doesn't print in the terminal.
I feel I'm missing something... I just started with this so... Help!

If name.py is executable, you can run it using:
./name.py
As for the #!, it is better to use as a first line:
#!/usr/bin/env python
This way path to python interpreter is not hardcoded, the first python found in $PATH is used instead.
Also: it makes your script to run in fresh environment (you can see man env for more information).

Related

Opening Python script mode on a MacBook

I have a MacBook air and have tried opening Python in terminal but when I open it, it opens Python interactive mode. Does anyone know how to open Python script mode please.
I’ve tried typing in things such as Python or Python 3 like safari suggests but that didn’t work.
There is no 'script mode'. You can create a Python script using TextEdit or another editor, save it as myfile.py, and then run it with python myfile.py.
for running what you are calling 'script version' of python you should choose a python file to run and make sure is written in the same or in a compatible version to the python you are running it with (python2, python3)
For running an example script:
python main.py
You need to be in the directory containing the file so make sure you are there before running the command. Using python runs the first version of python you installed, so if you want to use an other you should use:
python2 main.py
python3 main.py
etc
Assuming you've stored your script in a file named itworks.py, the simplest thing is to type the command python3 itworks.py in a terminal window after you've moved to the directory containing the script. Alternatively, you can type python3 followed by a space, then locate your python script in the Finder and drag and drop it into the terminal. This will expand to the full path to the file, allowing you to run a script located elsewhere than your current directory. Don't forget to press return...
In older versions of MacOS you could say python, but that uses python 2 which is no longer supported so you should go with python3 for any new development. (With MacOS Ventura, python 2 seems to have been removed.)
If you have multiple versions of python, you can use the command which -a python3 (or python) to see all versions on your PATH, and the order in which they will be found. PATH works on a first-come-first-served basis, but you can override by using the fully qualified path name to an alternative python.
Yet another solution, for when you want a more permanent script you will use many times in the future, is to use a "shebang" line as the first line of your script. For example, I wrote the following tiny demo:
#!/usr/bin/env python3
print('It works!')
The first line says to parse this script with the first python3 interpreter found in your current environment's PATH. You could replace that with an explicit path such as #!/opt/homebrew/bin/python3. Now make the script executable: chmod a+x itworks.py. You can now run the script from the current directory by typing ./itworks.py. (The leading ./ tells your shell you know it's in the current directory, and is intended as protection against trojan horse scripts.) If you want to be able to use the now-executable script from anywhere, add it to a directory on your path such as /usr/local/bin, and you'll be able to run it by just typing itworks.py.

Run Python code without using python name.py and ./name [duplicate]

This question already has answers here:
how to run python script without typing 'python ...'
(5 answers)
Closed 2 years ago.
I have a basic problem where I don't know how to run a Python script from command line in Ubuntu without using python keyword. So, I put a shebang in my Python script so I could run it as nameofthescript from the command line, but I only could do it by using ./nameofthescript. I want to be able to run it by just typing the name of the script in the cmd. I searched and tried everything I could on the web, but none is working. Any help is appreciated. Below is a simple code I wrote to test it.
I already tried chmod +x this file. Also this file is saved with no extension.
#!/usr/bin/python
import sys
def main(argv):
print(argv)
print("Hello")
if __name__ == "__main__":
main(sys.argv[1:])
The problem is with your $PATH variable.
When you go to run a command (without the "./" in front of it) Ubuntu looks in all the folders listed in your $PATH variable. Your can see it by running:
echo $PATH
If Ubuntu doesn't see the command in any of those folders, it will say that it can't be found.
You can solve this problem by altering your $PATH variable in your profile. Go to your home directory and open the ".profile" file (note the period in front) and add the following to the end:
PATH = "/path/to/folder/with/file/:$PATH"
However, if it's a program you could see yourself using a lot in the future and your don't want to clutter up your $PATH, I'd recommend sticking the finished command in your "/usr/local/bin" folder instead. I find that folder gets used as an "odd sock drawer" of programs you create/compile yourself, so I usually end up putting my personal tools in there rather than modifying my $PATH.
That's how it's supposed to work, not only for Python scripts but for any executable. See: Why do you need ./ (dot-slash) before executable or script name to run it in bash?
Please Try this one
On unix systems, Python scripts can be made executable using the following process:
Add this line as the first line in the script:
#!/usr/bin/env python
At the unix command prompt, type the following to make myexe.py executable:
$ chmod +x myexe.py
Move myexe.py into your bin directory, and it will be runnable from anywhere.
$ cp myexe.py /usr/bin
OR
$ cp myexe.py /usr/local/bin
So myexe.py
#!/usr/bin/env python
print("Hello This is executable python script")
Now Go to terminal and type myexe.py
$ myexe.py
Hello This is excutable python script
If you want to run by double-clicking remove .py extention
source link
I have found a way to solve this. I still include the shebang #!/usr/bin/env python3.6 at the top of Python script. Then I would go to cd /etc->sudo nano bash.bashrc, and at the very last line, all I did was add a line (alias nameofscript = "./nameofscript"). From there I restarted my Ubuntu, and was able to run my Python script just by the name of the script. Thank you everyone for the help.

Is there a way to shorten command line commands to open Python scripts?

I'd like to know if there is a way to shorten what must be written on the cmd.exe command line to run Python programs. As it is, I have a program called Calculator.py and if I wanted to run that I would have to write:
python.exe C:\Users\user_name\restofdirectory\Calculator.py
Basically I want to know if I could make the 'Python' folder on my computer default so I could just type python.exe Calculator.py or some other similarly short way of doing it so I didn't have to type the whole directory.
Create a cmd.exe shortcut somewhere handy (Desktop or whatever). Right Click, select properties. Under the Shortcut tab you'll have a "Start In" field. It'll be default to wherever your cmd.exe normally opens. But you can change it to any path you want (So set it to your python development folder)-- then opening that shortcut will always start cmd.exe in the python folder.
You don't need to type python.exe file.py --
Just type: python file.py
So in short, you'd click that shortcut and type python file.py and you are done.
If you have specific scripts you want to run frequently, you can create a cmd.exe shortcut for each one. Set the Start In path to their folder. Then update the link to cmd.exe like this:
c:\path\to\cmd.exe /k python file.py
That will open a cmd prompt and automatically run that specific script
Yes, you can cd into the folder first.
If python is in your default path you can create a folder and put all your python scripts in it. Then cd into that folder and type python Calculator.py. To test if python is in your path simply open up a cmd and type cd \ (which in your case should change your working directory to C:\) then type python. If you get an error saying the command python cannot be found then you have to add python to your path. Other wise you should be able to run cd C:\Users\user_name\restofdirectory\ and then execute the script python Calculator.py
create an environment variable, say, PyPath = C:\Users\user_name\restofdirectory
then your line would be:
python.exe %PyPath%\Calculator.py
or you just cd to C:\Users\user_name\restofdirectory, and run
python.exe Calculator.py
Add Python to your path:
SET PATH=%PATH%;C:\Python27\bin
then you can call python like this:
python myapp.py
If you have the Python Launcher for Windows (comes with Python 3.3+) installed, then it gets even easier. You just need to put shebang in your code:
#! python
The first time you run your code, Windows will pop up a dialog and ask you what program to use to run the script. The Python Launcher should be listed. Just choose that and away you go. Here's a fun little script from the page I linked earlier:
#! python
import sys
sys.stdout.write("hello from Python %s\n" % (sys.version,))
Once my Windows 7 box had the launcher installed and I told it what program to run, I could just call my script from cmd.exe like this:
my_script.py
Note: If you have a version of Python older than 3.3, you can download the installer here

Execute script in Python2 on Unix Command Line

Yes, I know I can do
python2 cal.py
What I am asking for is a way to execute it on the command line such as:
calpy
and then the command afterwards. I put in in a path and when I write cal.py in the command line:
/usr/bin/cal.py: line 5: print: command not found
I don't want to issue cal.py to run my script, I want it to be issued with calpy
I'm running Arch Linux if that helps, thanks. Sorry for my English.
In order for bash to know to run your script via the Python interpreter, you need to put an appropriate shebang at the start. For example:
#!/usr/bin/python
tells bash to run /usr/bin/python with your script as the first argument. I personally prefer
#!/usr/bin/env python
which is compatible with virtualenv. You also need to ensure that the permissions on your script allow it to be executed:
~$ chmod +x path/to/cal.py
Finally, in order to call cal rather than path/to/cal.py, you need to remove the .py extension and make sure that the directory containing cal is in your command search path. I prefer to add ~/bin to the search path by modifying the $PATH environment variable in ~/.bashrc:
export PATH=$HOME/bin:$PATH
then put my own executables in ~/bin. You could also copy (or symlink) cal to one of the system-wide binary directories (/bin or /usr/bin), but I consider it bad practice to mess with system-wide directories unnecessarily.
Ok, you need a couple of things for achive what you want.
First you have to tell your script "How" is going to execute/interpret it. You can do this writting
#/usr/bin/env python
at the very beggining of the file.
The problem you have is the system is trying to execute the script using bash. And in bash there is no print command.
Second you need give execution privileges to your script. And of course if you want to call your script through the command "calcpy", the script has to be called like that.
Put this (exactly this) as the first line of your script:
#!/usr/bin/env python

Run python source file from PowerShell

I'm trying to learn python but have some problem running source files from power shell. When I type 'python' it opens up and I can type python commands directly in the shell. I think this is called interactive mode. But when I try to run/execute a source file I get an error message: It sayys: Syntax error: invalid syntax.
I use 'python myfile.py' when I try to execute the script.
If I run the same file from IDLE it works just fine. Ana idea what I'm doing wrong?
Here is myfile.py. I'm running python 2.7
# filename: myfile.py
while True:
s = raw_input('Enter something: ')
if s == 'Quit':
break
print 'Lenght of the string is', len(s)
print 'Done'
You might have more than one version of Python installed and the version IDLE is using is newer. To see what version of python you have you can type >python -V at a command line. If that version looks appropriate then you might need the full path to the file as the second parameter. E.g >python C:\myfile.py.
If you installed Python correctly there is always a chance that just typing the name of the script will run it with python. E.g. >myfile.py
I always find that adding C:\Python27 to the %PATH% variable and .PY to the %PATHEXT% variable makes running scripts easier. In this case just >myfile should work.
Edit after Update:
Typing just >python with no parameters opens python in 'interactive mode' which is different from the batch or scripting mode that your script is intended for. If executed with arguments the first argument is taken as the file path and further arguments are passed to the script in the sys.argv list.
You will need to put the full path of the Python executable within the command line in order for it to work. You could check and ensure that your python exe is included in your Path among your system variables.
Disclaimer: I don't know PowerShell, but I do know cmd.exe.
I don't know why python myfile.py doesn't work, but assuming that PowerShell bears at least some similarity to cmd.exe, the following should probably work: myfile.py. That's right, just enter the name of the Python script and hit enter.
If you started by typing "python" in powershell you will need to get out of that script.
If you are in python type:
quit()
then type
python myfile.py
This should work if your python is installed correctly.
Try to type this in Powershell:
$env:path="$env:Path;C:\Python33
After this, command
python yourfile.py
should work.
This my sound silly, especially coming from a beginner.
Just save the file on your desktop. Open up powershell and drag the file directly into powershell and it opens. kind of tedious but it works

Categories