Running Python in CMD not working - python

I am a Python beginner and I am having trouble running Python from CMD. I have added the Python installation directory as a PATH variable (;C:\Python27). I am able to run the Python Interpreter from CMD, however when I issue a command like "python file.py command" from CMD, it returns "Error2, Python can't open, no such file/directory".
So what I do is go to "cd C:\Folder\Folder2\My_Python_Files", then type the "file.py command" each and every time. Is there faster or more efficient way of doing this? I am currently running Python2.7 on Windows 8.

When you run python <script>, it requires an actual path to the script being provided. You cannot specify "file.py" alone, unless it is right there in your current directory.
In windows, here are two steps you can take:
Associate .py files with python. Then you can run them directly without the python command as: /path/to/file.py
(right click a .py -> properties -> change to associate with python.exe)
Further step: Add a location to your PATH environment which will contain your python scripts. From there, you can just do file.py and it will be found in your search path.
So you could add C:\Folder\Folder2\My_Python_Files to your PATH and that is where you can store your executable python scripts.
Also you can set the PATH variable temporarily during a shell session:
SET PATH=%PATH%;C:\path\to\project

Just like PATH environment variable lists several directories for the system to search for executables, the PYTHONPATH do the same for Python to search for .py files. If you want scripts in a folder to be globally accessible (i.e. you can reference them by name just like you want, or you can import them from other scripts), add that folder to PYTHONPATH (create it if it doesn't exist).
Note that the command to invoke a script that is in your PYTHONPATH is:
python -m file [<script arguments>]
(i.e. use the -m option to treat it as a module, and don't use the extension .py)
Here's an article explaining in more detail how Python finds its source files (both in the command line and through import).
Note that you can also refer to the script by using its full path:
python C:\Folder\Folder2\My_Python_Files\file.py command
But by doing this, other files in the same folder that this script might reference through import might not work (since Python doesn't know where to search for them).

Unless the project's folder is in the PATH, you cannot call the file unless you are inside the project's folder. Don't create PATHs for projects, unless they are needed; it's unnecessary.
Just transverse to the file's directory and run the command inside the directory. That will work.
If the project will be used by other projects/files, you can use PYTHONPATH to set the directory, so the other projects can successfully access it.
Hope that helps.

Related

How is git able to run C scripts in the current directory as a command on terminal?

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.

Python Directory organization

I've just started a class that uses Python. At this point, I'm a complete beginner. I running Windows 10 via Parallels on an iMac. I'm have trouble organizing the directories within the "Python36-32" directory that is located on the VM (Windows). If I place a .py file in the main directory, I can run the file through the command prompt and see something like.
c:\Program Files\Python36-32>python first.py
hello
However, if I try to organized the file the file isn't read at all. For example, if I wanted the "first.py" file to run from a "web221" (the name of my class) subdirectory of "python36-32" and then try to open "first.py", I get:
C:\Program Files\Python36-32\web221>python first.py
'python' is not recognized as an internal or external command,
operable program or batch file.
I'd really like to keep all of the .py files I create for my class organized for obvious reasons. Any help would be appreciated.
When you execute from the one directory, the Python executable is present and Windows has no issue finding what to execute.
From the other directory though, Windows attempts to find the executable in your PATH and cannot see it.
Here is some help from the Python 3 docs:
https://docs.python.org/3/using/windows.html#excursus-setting-environment-variables
Specifically, try this as a test:
Windows allows environment variables to be configured permanently at both the User level and the System level, or temporarily in a command prompt.
To temporarily set environment variables, open Command Prompt and use the set command:
C:\>set PATH=C:\Program Files\Python 3.6;%PATH%
C:\>set PYTHONPATH=%PYTHONPATH%;C:\My_python_lib
C:\>python
However, this will only temporarily add the executable to your path. Try it to see if it works, and if it does, then you'll have the information you need to add it to your PATH variable permanently. Note: your directory is named differently, so you'll need to replace Python 3.6 with the name of the directory where Python is installed.
For the task of editing the PATH such that the changes persist from one command prompt session to the next, there's a related SO question that might be helpful:
How to add to the pythonpath in windows 7?

How can I add a python script to the windows system path?

I'm using windows cmd to run my python script. I want to run my python script withouth to give the cd command and the directory path.
I would like to type only the name of the python script and run it.
I'm using python 2.7
Create batch file inside the script's directory.
#echo off
echo.
python %~dp0\<script-name>.py %*
Put the above lines inside of it. And change according the script you want to run.
"%~dp0" is unique variable witch returns batch file's directory.
"%*" are the arguments passed through.
os.chdir(os.path.dirname(sys.argv[0]))
Also put the above line inside the script. The code above changes your python script's working directory to it's own directory. "sys.argv[0]" returns path of the script itself.
And add your script to Enviroment Variables. And run from command prompt using the batch file's name.
Make sure .py files are associated with the Python launcher C:\Windows\py.exe or directly with e.g. 'C:\Python27\python.exethen edit yourPATHEXTenvironment variable using (System Properties) to add;.PY` at the end. You can now launch Python files in the current directory by typing their name.
To be able to launch a given Python script from any directory, you can either put it in a directory that's already on the PATH, or add a new directory to PATH (I like creating a bin directory in my user folder and adding %USERPROFILE%\bin to PATH) and put it there.
Note that this is more a "how do I use Windows" question rather than a Python question.
1.Go to Environmental Variables >
system variable > Path > Edit
2.It look like this
Path C:\Program Files\Java\jdk1.8.0\bin;%SystemRoot%\system32;C:\Program Files\nodejs\;
3.You can add semicolon (;) at the end and add C:\Python27
4.After adding it look like this
C:\Program Files\Java\jdk1.8.0\bin;%SystemRoot%\system32;C:\Program Files\nodejs\;C:\Python27;

When using Python Windows Launcher, is there any way to prevent having to type full path?

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

How to run a Python script portably without specifying its full path

Is there a portable way to run a python script from a shell without writing its full path?
For example in Linux, I would like while in my home directory
cd ~
to be able to run a python script called run.py that is in say, ~/long/path/to/run.py, but I want to run it by simply typing
python run.py
instead of
python ~/long/path/to/run.py
I would hope for some kind of search path list that contains several directories just like the PATH variable, so that python run.py runs the first run.py it encounters in one of the directories.
I have considered turning run.py into an executable and adding its directory the system PATH variable, but could not find a portable way of making a python script executable.
EDIT
One year later after asking it, I am a bit less noob, and I see that my question was not very clear and did not make much sense, so after a question upvote I'll clarify some things.
1) Portable.
When I asked this I said portable. However what portable means is not clear in this case, and I did not give much emphasis to it.
the platforms: should work on POSIX (Linux, MacOS, etc.) and Windows
this still does not make much sense since windows uses cmd.exe, and POSIX uses sh, so each one could run the commands with a different syntax. So let's say that the most portable thing possible would be to feed the same input to both sh and cmd.exe, running the python script in both cases. In this case, you could run the same command from an ANSI C system function, which uses sh on POSIX and cmd on Windows. ANSI C being one of the few things that is common to Windows and POSIX, the question makes some sense in that case.
2) Executable
Next, the phrase turning run.py into an executable, is not very clear. By that I was talking about the Linux strategy of chmod +x run.py, add a shebang #!/usr/bin/env python, and adding its directory the system add ~/long/path/to/ the PATH enviroment variable. But then this won't work for windows because windows does not support an executable file metadata property like Linux and because /usr/bin/env does not necessarily exist in Windows.
3) Extension
Finally, in my head I was hoping for a solution that does not specify what kind of file run is, so that if someday we decide to make it, say, a perl file, no interfaces would change.
Therefore, writing run.py would be bad because it would specify the filetype; it would be better to be able to write just run
If the directory containing run.py is on the module search path (for example, PYTHONPATH environment variable), you should be able to run it like this:
python -m run
Here is the documentation on the -m command line option:
-m module-name
Searches sys.path for the named module and runs the corresponding .py file as a script.
You can make a python script executable by adding
#!/usr/bin/env python
to the beginning of the file, and making it executable with chmod +x.
Answer after the clarification edit
I prefer the following approach to the one suggested by #F.J. because it does not require users to specify the file type. Please note that this was not specified in the original question, so his answer to the original question was correct.
Lets call the file pytest.py to avoid conflicts with a possible existing run program.
On POSIX (MacOs, linux) do what #Petr said, which is based on what #alberge said:
chmod +x
add shebang #!/usr/bin/env python
create a directory and add it to path. Usual locations on Linux are: ~/bin/ for a single user, /usr/local/bin/ for all users
symlink (cp -s) the file under your PATH with basename pytest instead of pytest.py
On windows:
create a dir and add it to PATH. AFAIK, there is no conventional place for that, so why not C:\bin\ and ~\bin\?
add .PY to the PATHEXT environment variable so that Windows will recognize files with python extension as runnable files without requiring you to type the extension
associate python files with the python.exe interpreter (Windows Explorer > right click > check "Always use the selected program"). There is an option on the python installer that does this for you.
symlink pytest with extension into the dir under PATH (using Link Shell Extension from Windows Explorer or mklink name dest from cmd )
Now system( "pytest" ); should work in both systems ( sh under Linux, cmd under Windows )
Make python file executable (as "alberge" stated above)
Create some directory and put this directory into your PATH variable
In this directory, create links to your python scripts

Categories