noobiest question ever:
I'm trying to work with python via cygwin on my pc laptop - I have a file (foo.py) but python can't find it. The error it's giving me is:
$ chmod +x foo.py
chmod: cannot access `foo.py': No such file or directory
Is there a special location within the Cygwin folder that I need to save my foo.py?
Thanks!
AP
It's not python that can't find your file, it's the chmod command. C drive is mapped to /cygdrive/c in Cygwin, and D drive is mapped to /cygdrive/d and so on and so forth.
Are you in the same directory as the file when you are running chmod?
If your file is at C:\mycode\python\foo.py then you should either change to that directory first -
$ cd c:
$ cd mycode/python/
or as #Ahmed mentioned above, you could also run the command as
$ chmod +x /cygdrive/c/mycode/python/foo.py
But you only need chmod if your python script starts with
#!/bin/python
To execute such a file, you'd say
$ /cygdrive/c/mycode/python/foo.py
Or if you are in the same directory
./foo.py
If the first line of the python script isn't "#!/bin/python" then you can skip the chmod and just type
python /cygdrive/c/mycode/python/foo.py
You go right click on foo.py figure out its full path then do this:
chmod +x foos-full-directory/foo.py
And this should work for you and btw its not Python problem it's your pwd other than the foo.py working directory and you even didn't use python word in your command.
Related
I have a script I have downloaded and installed from GitHub that I am trying to add to my path. Although the script is in the path already somehow I can't run it unless I provide the full path.
echo $PATH
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin
/Users/me/bin/SCRIPT_FOLDER/
/Library/TeX/texbin
/Users/me/bin/SCRIPT_FOLDER/script.py
Since I am working on Catalina 10.15.7, I saw in other answers that I need to add the script to the .zshrc file, so I did so.
code .zshrc
export PATH=/Users/me/bin/SCRIPT_FOLDER/:$PATH
export PATH=$PATH:/Users/me/bin/SCRIPT_FOLDER/script.py
Despite this the script cannot be run except if I type the entire path
python /Users/me/bin/SCRIPT_FOLDER/script.py --h
What can I try to solve this?
script.py must be executable and the first line must be as shown below.
? echo $PATH
.:./bin:...
? ls
bin
? ls -l bin/script.py
-rwxr-xr-x. 1 x x 40 Mar 9 10:54 bin/script.py
? cat bin/script.py
#!/usr/bin/python
print('Hello world')
? script.py
Hello world
?
If the script is not executable use the chmod command like so:
chmod 755 bin/script.py
Like most command-line programs, Python doesn't consult your PATH for the arguments (e.g., script.py, given the command python script.py). Your PATH only matters when deciding how to resolve the command name (in this case, python). If script.py is in one of your PATH directories (like /Users/me/bin/SCRIPT_FOLDER/), it has the appropriate executable bit set, and it begins with an appropriate shebang line such as #!/usr/bin/env python, then you can run it with the command script.py.
I have a shell script which I want to run without using the "sh" or "bash" commands. For example:
Instead of: sh script.sh
I want to use: script.sh
How can I do this?
P.S. (i) I don't use shell script much and I tried reading about aliases, but I did not understand how to use them.
(ii) I also read about linking the script with another file in the PATH variables. I am using my university server and I don't have permissions to create a file in those locations.
Add a "shebang" at the top of your file:
#!/bin/bash
And make your file executable (chmod +x script.sh).
Finally, modify your path to add the directory where your script is located:
export PATH=$PATH:/appropriate/directory
(typically, you want $HOME/bin for storing your own scripts)
These are the prerequisites of directly using the script name:
Add the shebang line (#!/bin/bash) at the very top.
Use chmod u+x scriptname to make the script executable (where scriptname is the name of your script).
Place the script under /usr/local/bin folder.
Note: I suggest placing it under /usr/local/bin because most likely that path will be already added to your PATH variable.
Run the script using just its name, scriptname.
If you don't have access to /usr/local/bin then do the following:
Create a folder in your home directory and call it bin.
Do ls -lA on your home directory, to identify the start-up script your shell is using. It should be either .profile or .bashrc.
Once you have identified the start up script, add the following line:
PATH="$PATH:$HOME/bin"
Once added, source your start-up script or log out and log back in.
To source, put . followed by a space and then your start-up script name, e.g. . .profile or . .bashrc
Run the script using just its name, scriptname.
Just make sure it is executable, using chmod +x. By default, the current directory is not on your PATH, so you will need to execute it as ./script.sh - or otherwise reference it by a qualified path. Alternatively, if you truly need just script.sh, you would need to add it to your PATH. (You may not have access to modify the system path, but you can almost certainly modify the PATH of your own current environment.) This also assumes that your script starts with something like #!/bin/sh.
You could also still use an alias, which is not really related to shell scripting but just the shell, and is simple as:
alias script.sh='sh script.sh'
Which would allow you to use just simply script.sh (literally - this won't work for any other *.sh file) instead of sh script.sh.
In this example the file will be called myShell
First of all we will need to make this file we can just start off by typing the following:
sudo nano myShell
Notice we didn't put the .sh extension?
That's because when we run it from the terminal we will only need to type myShell in order to run our command!
Now, in nano the top line MUST be #!/bin/bash then you may leave a new line before continuing.
For demonstration I will add a basic Hello World! response
So, I type the following:
echo Hello World!
After that my example should look like this:
#!/bin/bash
echo Hello World!
Now save the file and then run this command:
chmod +x myShell
Now we have made the file executable we can move it to /usr/bin/ by using the following command:
sudo cp myShell /usr/bin/
Congrats! Our command is now done! In the terminal we can type myShell and it should say Hello World!
You have to enable the executable bit for the program.
chmod +x script.sh
Then you can use ./script.sh
You can add the folder to the PATH in your .bashrc file (located in your home directory).
Add this line to the end of the file:
export PATH=$PATH:/your/folder/here
You can type sudo install (name of script) /usr/local/bin/(what you want to type to execute said script)
ex: sudo install quickcommit.sh /usr/local/bin/quickcommit
enter password
now can run without .sh and in any directory
Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.
Just make sure to add Shebang (#!/bin/bash) line at the starting of your script and make the script executable(using chmod +x <File Name>).
Here is my backup script that will give you the idea and the automation:
Server: Ubuntu 16.04
PHP: 7.0
Apache2, Mysql etc...
# Make Shell Backup Script - Bash Backup Script
nano /home/user/bash/backupscript.sh
#!/bin/bash
# Backup All Start
mkdir /home/user/backup/$(date +"%Y-%m-%d")
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
# Backup All End
echo "Backup Completed Successfully!"
echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"
chmod +x /home/user/bash/backupscript.sh
sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript
change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)
Enter "#!/bin/sh" before script.
Then save it as script.sh for example.
copy it to $HOME/bin or $HOME/usr/bin
The directory can be different on different linux distros but they end with 'bin' and are in home directory
cd $HOME/bin or $HOME/usr/bin
Type chmod 700 script.sh
And you can run it just by typing run.sh on terminal.
If it not work, try chmod +x run.sh instead of chmod 700 run.sh
Make any file as executable
Let's say you have an executable file called migrate_linux_amd64 and you want to run this file as a command like "migrate"
First test the executable file from the file location:
[oracle#localhost]$ ./migrate.linux-amd64
Usage: migrate OPTIONS COMMAND [arg...]
migrate [ -version | -help ]
Options:
-source Location of the migrations (driver://url)
-path Shorthand for -source=file://path
-database Run migrations against this database (driver://url)
-prefetch N Number of migrations to load in advance before executing (default 10)
-lock-timeout N Allow N seconds to acquire database lock (default 15)
-verbose Print verbose logging
-version Print version
-help Print usage
Commands:
goto V Migrate to version V
up [N] Apply all or N up migrations
down [N] Apply all or N down migrations
drop Drop everyting inside database
force V Set version V but don't run migration (ignores dirty state)
version Print current migration version
Make sure you have execute privileges on the file
-rwxr-xr-x 1 oracle oinstall 7473971 May 18 2017 migrate.linux-amd64
if not, run chmod +x migrate.linux-amd64
Then copy your file to /usr/local/bin. This directory is owned by root, use sudo or switch to root and perform the following operation
sudo cp migrate.linux-amd64 /usr/local/bin
sudo chown oracle:oracle /user/local/bin/migrate.linux.amd64
Then create a symbolic link like below
sudo ln /usr/local/bin/migrate.linux.amd64 /usr/local/bin/migrate
sudo chown oracle:oracle /usr/local/bin/migrate
Finally add /usr/local/bin to your path or user profile
export PATH = $PATH:/usr/local/bin
Then run the command as "migrate"
[oracle#localhost]$ migrate
Usage: migrate OPTIONS COMMAND [arg...]
migrate [ -version | -help ]
Options:
-source Location of the migrations (driver://url)
-path Shorthand for -source=file://path
-database Run migrations against this database (driver://url)
-prefetch N Number of migrations to load in advance before executing (default 10)
-lock-timeout N Allow N seconds to acquire database lock (default 15)
-verbose Print verbose logging
-version Print version
-help Print usage
Commands:
goto V Migrate to version V
up [N] Apply all or N up migrations
down [N] Apply all or N down migrations
drop Drop everyting inside database
force V Set version V but don't run migration (ignores dirty state)
version Print current migration version
Make the script file as executable by using file's properties
Create alias for the executable in ~/.bashrc. alias <alias namme> = <full script file path>'
refresh the user session to apply it. source ~/.bashrc
Just to add to what everyone suggested. Even with those solutions, the problem will persist if the user wants to execute the script as sudo
example:
chmod a+x /tmp/myscript.sh
sudo ln -s /tmp/myscript.sh /usr/local/bin/myscript
typing myscript would work but typing sudo myscript would return command not found.
As sudo you would have to still type sudo sh myscript or sudo bash myscript.
I can't think of a solution around this.
Just:
/path/to/file/my_script.sh
I have a folder named test-folder with two files.
# file name: demo.py
print('hello world')
# file name: script.sh
python3.7 demo.py
The test-folder is present inside /home/username/Documents/
I have exported the above path to the .bashrc.
Now when I try to execute the script.sh using the following command,
bash script.sh
I get the following error
python3.7: can't open file 'demo.py': [Errno 2] No such file or directory
How can I solve this? I'm on Ubuntu 18.04
Move to the folder containing the file :
$ cd /home/username/Documents/test-folder
after making sure you are in the folder ccontaining the file try:
$ python file_name.py
if it doesn't work try the full path to python and the full path to the file like this:
$ /usr/lib/python3.7 /home/username/Documents/test-folder/file_name.py
If you want to use script.sh from anywhere, your approach won't work.
When executing $ bash script.sh, the file script.sh is expected to be located in the working directory.
You can use absolute paths to solve this:
# filename: script.sh
python3.7 /home/username/Documents/test-folder/demo.py
Try executing this with bash /home/username/Documents/test-folder/script.py.
You can achieve your goal in an arguably simpler way by adding /home/username/Documents/test-folder to your PATH, adding a shebang to demo.py and making demo.sh executable.
$ export PATH=/home/username/Documents/test-folder:$PATH
$ chmod +x /home/username/Documents/test-folder/demo.py
demo.sh will look like this with a shebang:
#!/usr/lib/python3.7
print('hello world')
and can be executed from anywhere with $ demo.sh.
It works for me. Is there anything about your setup that is different than mine?
$ cat demo.py
print("Hello World")
$ cat script.sh
python3.7 demo.py
$ tree
.
└── test-folder
├── demo.py
└── script.sh
1 directory, 2 files
$ cd test-folder/
$ bash script.sh
Hello World
Edit: Try the following.
$ cat script.sh
python3.7 "`dirname "$0"`/demo.py"
If your script.sh file is only there to run the Python script, it’s not needed. Instead make the Python script itself executable.
(1) add this as the first line in your Python file — this tells Unix which interpreter to use when running this file:
#!/usr/bin/env python37
(2) make your Python file executable so it can be run directly:
chmod +x demo.py
(3) put that file on the path, e.g. a path you set via a Bash config file, or one that’s already on the path like /usr/local/bin.
Now any time you give the command demo.py your script will run. Note the .py extension isn’t required — you can name the file anything you like.
I'm writing a python script which will be placed in a location. I want to execute it just like a command. for ex.
$ find_branch test
where find_branch is a script placed in anywhere in the system.
I would like to know how to achieve this. I can run it on the place where the script is present by chmod u+x on the script and removing the .py from the script
sudo nano /usr/bin/testpyscript
Then inside the script:
#!/usr/bin/python
print("I'm a python script")
Give it x permission:
sudo chmod +x /usr/bin/testpyscript
Now you can use it as a regular command:
bash-4.2$ testpyscript
I'm a python script
It doesn't have to be exactly at /usr/bin, any location that is inside your $PATH will do. Let's say you want it to be located at some folder inside your home directory, you could do something like this:
pwd
/home/brunorb
mkdir somedir
sudo mv /usr/bin/testpyscript somedir/
export PATH=$PATH:/home/brunorb/somedir/
testpyscript # from any folder in the system
I'm a python script
Make sure python has been added to your path and #!/usr/bin/python is located at the top of your script.
Note You could just try adding your script to your /usr/local/bin/ directory and give it the proper permissions.
sudo cp <your script> /usr/local/bin/
You have a number of options on how to achieve this.
Add the location where you put the script to your PATH environment variable, for example in your ~/.bashrc script:
export PATH="${PATH}:/folder/where/you/put/the/script"
Install the script to a location that is already on your path. It does not have to be a system folder like /usr/bin. Many default Bash setups will include ~/bin in your PATH.
Give the full path to your script on the command line:
/folder/where/you/put/the/script/find_branch test
Run the script through Python. This is very similar to option #2:
python /folder/where/you/put/the/script/find_branch test
Create an alias for the script in your environment. In bash you would do something like the following in your ~/.bashrc:
alias find_branch='/folder/where/you/put/the/script/find_branch'
OR
alias find_branch='python /folder/where/you/put/the/script/find_branch'
For options #1, #2, #3 and #5a to work properly, you should have a shebang with the version of python as the first line of the script. Any of the following will do, depending on how you have/want your environment set up:
#!/usr/bin/python
#!/usr/bin/python2
#!/usr/bin/python3
#!/usr/bin/env python
#!/usr/bin/env python2
#!/usr/bin/env python3
Finally, you do not have to remove the .py extension from the script if you do not want to. Many bash scripts have a .sh extension, for example, which does not prevent them from running as-is. You just have to include the extension in the name of the script when you run it.
Massive apologies for this embarrassing question—
I'm using my MacBook Pro, running snow leopard, and using Python 2.7.1. Trying to run my first script and all the first pages of all my tutorials are laughing at me:
Let me preface with:
$ whereis python
/usr/bin/python
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
(Is this my issue?)
I wrote helloworld.py to /users/charles in vim:
$ vim helloworld.py
#!/usr/bin/python
# Hello World Python Program
print "Hello World!";
When trying to run it from terminal:
$ helloworld.py
-bash: helloworld.py: command not found
When trying to run it from python:
$ python
>>> helloworld.py
Traceback (most recent call last):
File :<stdin>", line 1, in <module>
NameError: name 'helloworld' is not defined
From Dive Into Python (not sure if this is pertinent):
$ python
>>> import sys,os
>>> print 'sys.argv[0] =',sys.argv[0]
sys.argv[0]=
>>> pathname=os.path.dirname(sys.argv[0])
>>> print 'path=',pathname
path=
>>> print 'full path=',os.path.abspath(pathname)
full path= /Users/charles
I'm befuddled! Do I need to alter one of my paths so it finds my script?
I'm absolutely new to programming, I actually just found out that terminal was something you could use.
Thanks!
Let's start with the first error you received. Understanding error messages is important.
-bash: helloworld.py: command not found
This indicates that helloworld.py is not a command that can be executed. To run the file, you then have two options:
Run it using the python interpreter. python helloworld.py
Make the file executable and then run it directly. ./helloworld.py
To make files executable in a *nix environment, you have to change their mode to allow execution. In order to do this, you use the chmod command (man chmod for more info).
chmod +x helloworld.py
This assumes that you are in the directory containing the helloworld.py file. If not, cd there first or use the full path.
The ./ is necessary because it tells the shell to run the file located here, not by looking in $PATH. $PATH is a list of possible executable locations. When you try to run helloworld.py directly, the shell tries to look for it in $PATH. You want to run the local file, so you have to prefix it with ./, which means "from here".
As an aside, note the first line of your python script:
#!/usr/bin/python
This is called a shebang line and tells system to use the /usr/bin/python executable to load the file. Internally, that means that the program loader will be doing /user/bin/python helloworld.py.
Finally, when you called python with no arguments, you were dropped into an interactive Python interpreter session. >>> helloworld.py in this environment is not referencing the file of that name, it's just interpreted as python code. Invalid python code. This is why you get your second error, NameError: name 'helloworld' is not defined.
To turn a Python module or script into a standalone program on a UNIX system you have to do two things:
1.) Make sure you have the "shebang" in the top of your script:
#!/usr/bin/python
2.) Make sure the script file is executable. This is done using the chmod command:
chmod +x /path/to/helloworld.py
/path/to/ being the fully qualified file path to your script. If it's in the current directory, then you can omit the path.
% ls -l
total 0
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rw-r--r-- 1 jathan jathan 0 2011-04-13 15:28 helloworld.py
It's in my current directory, so let's make it executable!
% chmod +x helloworld.py
% ls -l
drwxr-xr-x 2 jathan jathan 60 2011-04-13 15:28 ./
drwxrwxrwt 12 root root 6.5K 2011-04-13 15:28 ../
-rwxr-xr-x 1 jathan jathan 0 2011-04-13 15:28 helloworld.py*
See the "x"s in the permission bits on the left? You've done it! Now we can run it:
% ./helloworld.py
Hello World!
Lastly, never use semicolons as line-endings in Python. It's not required and it's ugly!
Wanted to add my 2 cents: Apart from permissions and path answers above, there is one more situation where you may still face the same error.
In-spite of correct permissions and the shebang header, you may still get the same "Command not found" error if you've originally written the file in Windows and copied it over to Linux. Due to differing line-ending characters, there will be extra '\r' characters on the lines.
This happens because there are non-printable characters in the file. Examing it by doing:
cat -v <filename>:
#!/usr/intel/bin/python^M
The extra "^M" is the problem. Use 'dos2unix' to convert the file and then it'll run fine.
as others said you should chmod +x your file to make it executable and if you don't want to put "./" in your coomand line you should add your current place as system path:
export PATH=$PATH:.
If you're already within python, the syntax to load your script is not helloworld.py :
import helloworld
or
from helloworld import *
you only use the extension .py when you're running python with a script as a command line argument.
No need to apologize, have to start somewhere, and the error messages can be cryptic when you're having basic syntax problems.
Make sure your terminal's current working directory is where your .py file is.
EDITED:
try doing /usr/bin/python helloworld.py on commmand line