I've just started learning Python using Learning Python by Mark Luts. In his book he offers an example of a simple script that is called through the Windows shell. In the example, he calls is as follows:
C:\code> python script1.py
I've gone and modified the Environment Variables on my machine so that I can call
C:\User\Example> python
to open up the interpreter and I can also call something like
C:\User\Example> script1
to run a script that I've written and placed in my desired directory. My issue is that I can not call
C:\User\Example> python script1.py
in my command line the same way he does in the book. He's mentioned something about a PYTHONPATH Environment Variable, however, this variable isn't present on my machine. I only have 'path', 'TEMP', and 'TMP'. Particulary, when I try to make such a call I get the error
python: can't open file 'script1.py': [Errno 2] No such file or directory
What do I have to do in order to get this sort of command to work properly on the command line?
From the book (p. 44, 4th Ed):
Finally, remember to give the full path to your script if it lives in a different directory from the one in which you are working.
For your situation, this means using
C:\User\Example> python C:\User\Example\my_scripts\script1.py
You could write a batch file that looks for the script in a predefined directory:
#echo off
setlocal
PATH=C:\User\Example\Python36;%PATH%
SCRIPT_DIR=C:\User\Example\my_scripts
python %SCRIPT_DIR\%*
You are calling python from within the context of C:\User\Example, and passing it a name of a file you want to run through the intepreter (script1.py). It is clear that the PATH variable is setup correctly such that you can call python from anywhere on you computer, since we can see that it is running but not actually able to find your script.
However, you stated in the comment that your scripts are actually located in C:\User\Example\my_scripts. In other words, you are passing python a name of a file that doesn't exist!! (at least from the contect of C:\User\Example).
You need to be in the directory of the script in order for the python executable to be able to find it.
Alternatively, you can run the python command and give it more information as to where the script is. For instance, you could run python .\my_scripts\script1.py if you are running from within the contect of C:\User\Example and your scripts are in C:\User\Example\my_scripts.
Related
I feel a little foolish that I don't know this, but I tried to do it today and was surprised when it didn't work....
I have a directory C:\test with a demo script, lets call it demo.py
If i am in C:\test then I can just do python demo.py. Easy
I could also use a relative path, so from C:\, it's python test\demo.py
What if C:\test is on the path?
I was expecting to be able to now do python demo.py from anywhere however...
python: can't open file 'demo.py': [Errno 2] No such file or directory
I feel foolish because I thought this was straightforward, but I have searched around and have not found a solution. Am I fundamentally misunderstanding something here about how the Python interpreter finds scripts to run? I don't think this is anything to do with PYTHONPATH, as I understood that to relate to loading of modules inside scripts.
This is on Windows 7, by the way.
The PATH is only used to search for commands. A first way is that a Python script can be used directly as a command and in that case the PATH will be used: just use demo.py instead of python demo.py.
It will rely on OS specific ways. On Windows, file type (given by the extension - here .py) can be given default application to process them, while on Unix-like, the first line of a script can declare the program that will process it.
Alternatively, python allows to launch a module that will be searched in the PYTHONPATH (not PATH) by using python -m module or for Windows py -m module.
I want to know how (if there is a way) to write a function and have it automatically defined when you start a python shell, or to keep certain defined functions after the shell closes so you don't have to keep re defining it if you use it a lot.
Yes, you can, you need to set your environment variable PYTHONSTARTUP to a python script you would like to be executed at every python startup.
By convention, such files are named by adding the rc suffix to the program name you're trying to tweak, and are usually located at the root of your home directory. In that case I would create the python file under $HOME/.pythonrc and then run export PYTHONSTARTUP=~/.pythonrc (for UNIX-like systems, it could be slightly different on Windows if you don't have a MinGW or equivalent).
Here's an example of .pythonrc file that you can play with: https://gist.github.com/twneale/5245670
I have been looking into bash and shell recently and been trying to work out how git is able to make a terminal command that runs C scripts in the current directory e.g git init, git push/pull etc.
I have been trying to simulate it in python, by making an executable python script in my home directory,
#!/usr/bin/env python
import os
print("current_dir: ",os.getcwd()) #prints /Users/usr/folder/script.py
Then I create a .command file that calls the python script
cd
cd FOLDER/
python3 SCRIPT.py
and editing the bash profile to export a variable to run the .command file.
export mycommand=/Users/urn/folder/command.command
Although this is not even nearly close to the way git achieves its command line. For example, when I run my script is not actually a terminal command it is just an environment variable, hence the $.
$mycommand
Secondly, this goes to the directory of the python file and runs the script from with that directory, therefore the output will always be the same
/Users/usr/folder/script.py
Although in git it runs the file in the current directory. Therefore the print statement would change depending on the terminal directory.
How am I able to create my own 'terminal command' such as git init to run my python script in whatever directory I'm in. Ps, I'm on mac.
Any help would be greatly appreciated :)
It sounds like you are missing at least two basic concepts:
The search path: when you issue a command that is not a shell function or built-in and that has an unqualified name (one with no / characters), the shell searches a list of zero or more directories for a matching executable file. This list of directories is the "path", and it is stored in the PATH environment variable. You can change it if you wish. This is how the shell finds the git program when you do not specify a path to it.
Executable scripts: Python, shell, Perl, etc. programs that must be run via an interpreter can be made executable by name alone by including an appropriate shebang line as the very first line and assigning an executable mode. You include an appropriate shebang line in your example Python program, in fact, but you seem not to understand its significance, because you explicitly launch the script via the python3 command. The shebang line is just another comment to Python, but it is meaningful to the system.
It seems like you probably also are missing some other concepts, like the fact that your script doesn't need to be in the current working directory for you to run it via the python3 launcher, path notwithstanding. Just specify its full pathname. Alternatively, Python has its own variation on a path, PYTHONPATH, by which it can locate modules and packages. These are alternatives, however -- the first two points are enough to achieve your apparent objective. Specifically,
Keep the shebang line in your script, though your default python is probably v2.7, so if you really want to run it specifically via python3 then modify the shebang line to say so:
#!/usr/bin/env python3
Make sure the file has executable mode. For example,
chmod 0755 /Users/urn/bin/SCRIPT.py
Then you should be able to execute the script from anywhere via its full pathname.
To access it from anywhere via its simple name, ensure that the directory containing it is in your path. For this purpose, it would be wise to choose an appropriate directory, such as /usr/local/bin or /Users/urn/bin (you may need to create the directory first). Whichever you choose, ensure that that directory is in your PATH. For example, edit /Users/urn/.bash_profile, creating it if necessary, and ensure that it contains (say) the commands
PATH=$PATH:/Users/urn/bin
export PATH
That will take effect in new Terminal windows you open afterward, but not automatically in any that are already open. In those windows, you will be able to run the script, from anywhere, via its simple name.
In Windows 8, I often use the Python Windows Launcher like
py C:/long/long/long/long/long/path/to/prog.py ...
Is there any way to set some environment setting, such as PATH or PYTHONPATH etc, to prevent having to type the full path to prog.py?
From my basic knowledge/research, PATH only helps with the py part of the command line and PYTHONPATH only helps with imports within prog.py, so how do I deal with the path to prog.py itself??
Notes:
I cannot modify the code, not even the "shebang" line, since it is needed to work on other platforms.
I cannot cd to the directory containing the programs to run them, because the programs will do something based on the directory they're run in (they'll modify the files in the directory they're run in).
I know that if I associate .py extension with the Python Windows Launcher, then I can run prog.py as the first item in the command line, and thus use PATH, but currently my .py extension is associated with my favorite editor and I'd like to keep it that way if possible (so I can double-click any Python file in Windows Explorer and edit it).
However, if someone suggests a solution where I can have a different association for Windows Explorer versus the command line, then that could be a potential solution! (i.e. in Windows Explorer, .py opens with the editor, while on command line, .py runs with Python Windows Launcher)
Add your long path to PYTHONPATH, then invoke your program as such:
python -m prog
Python will search for a module called prog and then run it as the main module.
Answer to my own question: Actually, I'm so silly. I could just set a variable for each program path (there are only a few programs paths), i.e.. prog=C:/long/path/to/prog.py and then do py %prog% .... I guess I figured out an answer to my own question that was acceptable to me.
Update: I just found something even better. I can do
doskey prog=py C:/long/path/to/prog.py $*
and then simply prog ... afterward
Now I just have to do some crazy stuff to get the doskey command into a file that will be run every time I start a console, as described here: https://stackoverflow.com/a/21040825/5182136
I am new to programming, and Python is my first language.
I've added Python to my Path, but when I use the Command Prompt, I don't have to add python before myscript.py as opposed to many tutorials I've seen. Here is an example:
C:\User\MyName>Welcome.py
Welcome to Python
Python is fun
When I enter 'python', there is a subsequent error:
C:\User\MyName>python Welcome.py
python: can't open file 'Welcome.py': [Errno 2] No such file or directory
Do I really need the 'python'?
Thanks in advance!
If you followed the Python on Windows FAQ, it seems that the standard Python installer has already taken the liberty of associating .py files with an open command to ..\..\Python\python.exe "%1" %*.
How do I make Python scripts executable?
On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (D:\Program Files\Python\python.exe "%1" %*). This is enough to make scripts executable from the command prompt as ‘foo.py’. If you’d rather be able to execute the script by simple typing ‘foo’ with no extension you need to add .py to the PATHEXT environment variable.
Who'd have thunk! This isn't the way it used to be four years ago when I first installed Python on my Windows machine.
Yes and no.
It really depends on how the script is written.
On most unix systems (Linux, Mac OS), you could include #!/bin/python to the top of (as the first line of) your script and therefore execute it by just calling the filename on the command line. That first line tells the shell that this file contains a python program. The shell then uses the python interpreter to execute the file (translation: it translates your $ Welcome.py to $ /bin/python Welcome.py <- note that python is being called explicitly and that it's the same path as what's on the first line of your file).
Presumably, the Windows OS can also be instructed in the same way, though I have never been able to do it myself, nor have I tried very hard (I moved away from windows about 5 years ago). This is why you'll need to explicitly call python.
Calling python tells the OS: "hey! open that program called python and tell it to run the file Welcome.py". This is exactly what the command /bin/python Welcome.py does on a unix system
When you install python on windows with a regular installer, .py files are associated with the python.exe you installed. When you type Welcome.py, Windows searches the local directory and then all paths in the PATH variable for a program called Welcome.py and runs it via python. Since this worked for you, it means that Welcome.py is somewhere on your path or in your local directory.
You can figure out your file associations with the assoc .py and ftype Python.File commands. The echo %PATH% and echo %PATHEXT% commands are also useful.
When you type python Welcome.py, Windows searches all paths in the PATH variable for a program that starts with 'python' and ends with an extension in PATHEXT. It finds 'python.exe' and runs it. Python in turn looks for a script called Welcome.py in the current directory. Since this didn't work for you, it means that Welcome.py is not in your local directory. It would have worked if you had given the right path to Welcome.py.
You can find out where Welcome.py is with the (not surprisingly) where Welcome.py command.
If you only have a single python installation, there is no need to call python myscript.py ....