Running python scripts from DOS or python shell without path name - python

I was attempting to edit the registry so when I type into either the python shell or a DOS window:
python sample.py
I want it to go to the directory that I save my .py files to and run the file without me having to type:
python C:\PythonPractice\sample.py
any ideas?

For the DOS window:
set VARIABLE=yourpath
python %VARIABLE%\sample.py
So for your example you could do this:
set p=C:\PythonPractice
python %p%\sample.py
You can setup this permanently by going to "Control Panel">>"System">>"Advanced system settings">>"Environment Variables". You probably want to add a variable to your account, unless you want it to affect all of the system profiles. A restart is probably required.

#echo off
c:
CD c:\py
c:\python271\python.exe %1
Save that as py.bat in a dir on your PATH. Change c:\py to the directory of your scripts.
You can call your scripts from everywhere like this:
C:\Windows>py hallowelt.py
Hallo!

A slight improvement to Jacob's answer:
#echo off
pushd c:\py
c:\python271\python.exe %*
popd
Save this as py.cmd in one of the directories from your your PATH environment variable. Then you can call
py sample.py arg1 arg2 ...
This works with any number of arguments.
But, as wberry mentioned, you could change the working directory from inside your Python script as well, if you really need to (but I think that's a bad idea):
os.chdir(os.path.abspath(os.path.dirname(__file__))) #untested
While this isn't exactly an answer to your question, I recommend using the following pattern:
Say, I have a Python script c:\mydir\myprog.py that requires special environment variables (PATH, ORACLE_HOME, whatever) and maybe it needs a particular working directory.
Then I create a file myprog.cmd in the same directory:
#echo off
setlocal
set PATH=...
set ORACLE_HOME=...
pushd %~dp0
python %~dpn0.py %*
popd
endlocal
The pushd/popd part is for changing and restoring the working directory.
For an explanation of the %~... Syntax, type
help call
at the command prompt.
This approach gives you full control about the environment of your Python program.
Note that the python call is generic: If you need a second Python script otherprog.py, then just save a copy of myprog.cmd as otherprog.cmd.

Related

Call a Python script (in a directory in the PATH) from command line with Windows

With Linux, if you create a file mycommand with +x permission in a folder which is in the PATH, containing a Python shebang #!..., then calling mycommand from command line works, no matter the current directory.
How to have the equivalent on Windows? i.e. I have a folder D:\myscripts\ which is in the PATH, containing a few personal scripts like mycommand.py.
How to make that calling mycommand or maybe just python mycommand from commandline will work, no matter the current working directory?
TL;DR: I'd like to avoid to have to do
python D:\myscripts\command.py
each time I want to call every-day-use personal scripts from D:\myscripts\
Note: .py files are associated with my text editor (i.e. when double-clicking on a .py file, it is opened with the text editor) and I want to keep this.
Solution 1
I finally did like this:
put D:\myscripts\ in the PATH (with setx, see How to update system PATH variable permanently from cmd?)
create a batch file: D:\myscripts\mycommand.bat containing:
#python d:\myscripts\mycommand.py
That's it!
Solution 2
Here is a solution from various comments from #ErykSun:
Open the system environment variables editor and ensure that "D:\myscripts" is in PATH (do not use quotes) and ".PY" is in PATHEXT (do not use quotes).
Create a test file D:\myscripts\test_command.py with the line import sys; print(sys.executable); print(sys.argv).
In a new command prompt that was opened from Explorer (to get the updated environment variables), run the test script from another directory as test_command spam eggs. If it runs with the expected Python installation and the command-line arguments "spam" and "eggs" are correctly passed, then you're done.
When double-clicking and running at the command prompt, the shell executes the default action for the filetype. If the filetype doesn't explicitly define a default action, the shell uses the "open" action, and if that's not defined it uses the filetype's first defined action, whatever that is. Python configures an "open" action for its "Python.File" filetype and additional context-menu (right-click) actions for editing with IDLE.
There are other directions you can go with this. You can use shell links. Add ".LNK" to PATHEXT and remove ".PY". Then for each script that you want to run, create a shell link (.LNK shortcut file) in D:\myscripts that runs the script explicitly as "path\to\python.exe" "\path\to\script". Leave the working directory field empty, so that it inherits the working directory of the parent process. For example, create D:\myscripts\test_command.lnk to run D:\myscripts\test_command.py.
In this case, you would run the script as test_command, which will find and execute "test_command.lnk". To get the default Sublime edit action, you would explicitly run test_command.py with the ".PY" extension.
Solution 3
Create an .exe file in c:\python37\scripts\ with this method: How to create a .exe similar to pip.exe, jupyter.exe, etc. from C:\Python37\Scripts?
but it's more complicated since it requires a package, etc.

How to make a command that runs Python a script in Windows command line?

Background:
I'm using Windows. I know some of programming with python. I don't know much about batch, which I think I might need to do what I want.
I will show a example so it becomes more clear what I'm trying to do.
Example:
When using git, after you install it, you can call the git command from anywhere of your computer, you can execute git commands, like git init and this will create a git file in your current folder.
I don't know exactly how git works or what language they use but I want to do the same thing, create my own command that I can execute from anywhere in my computer after I "install" my program.
What I'm trying to do:
I want to make my own command and when I call it, it executes a python script.
e.g.
I install my program and it creates a command called myprogram and when I type myprogram in the command line, it's like if I typed python myprogram.py. And myprogram -someargument would be the same as python myprogram.py -someargument.
What I tried until now:
I'm searched for How to make a environment variable that runs Python script? but I never get exactly what I want, is always something like How do I set environment variable using Python script?.
Maybe I'm making the wrong question and the result I want are not showing?
I'm looking for a explanation on how to do this or at least a tutorial/guide.
Edit 1:
As UnholySheep said in the comments, it's not environment variable, its commands, so I changed the question even does what I want to know is the same thing.
Files you need:
First you need a python script (obviously) so I created a file called myprogram.py that have this simple line:
print("This should be from a command")
After you need to make a batch file, in my case I used a .cmd file called myprogram.cmd that have:
#ECHO OFF
python_directory\python.exe python_script_directory\myprogram.py %*
Configurations to make:
You need to set in PATH environment variable the location of the batch file batch_file_directory\myprogram.cmd
And now if you execute in the command line myprogram it will print This should be from a command.
You can also use .exe or .bat files.

Set-Variable powershell. How do I link a variable to an exe file?

I'm quite new to the PowerShell environment, but I'm supposed to use it for "Learn python the hard way". In the mac terminal you can just type:
python script.py
In PowerShell on Windows this does not work. I'd like to be in any folder in my computer and execute python on a script in that folder. For that I believe the best thing to do is create a variable that calls python.exe instead of having to list the path every time.
I have tried declaring a python variable in the Command Prompt window but they don't seem to carry over.
Any small additional information like the name of the action I'm trying to do would be helpful!
This is actually pretty easy to do using the Set-Alias instead of Set-Variable. You will basically just pick up the path and how you want to reference it in your code.
I do this often for when I need to call 7z.exe (aka 7-zip) in my scripts:
$szPath = "$env:ProgramFiles\7-zip\7z.exe
if (Test-Path $szPath) {
Set-Alias sz $szPath -Scope Global
}
Then anytime I want to call that program and need to use variables specific to 7-zip I just call it:
sz l $filename
You should be able to do the same with python executable:
Set-Alias python '<Path to Python.exe' -Scope Global
I only use Global scope so it ensures I can get to anywhere in my process, so if you have any child scripts that may get called the alias is still usable.
Your other option would be to set the python executable path in your environment variables for Windows. Then you would be able to just call python as well.
I don't know how to do this for python, but this example is from the response to "help alias"
PS> new-item -path alias:np -value c:\windows\notepad.exe
Now, "np" will be an alias for notepad, and it can be used as a command, like any other alias.
This has nothing to do with variables. You just need to ensure that Python is on your PATH.
If C:\Python27 is your python directory, then :
$newPath = [Environment]::GetEnvironmentVariable("Path", "Machine") + ";C:\Python27\"
[Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
will add it to your PATH environment variable, and then you'll be able python everywhere you want to.

Notepad++ cannot find filepath

I'm trying to run a Hello World program in Python I wrote in Notepad++ using the NppExec plugin, but instead of printing, I'm getting
python C:\Users\Sam\Desktop\Test.py
CreateProcess() failed with error code 2:
The system cannot find the file specified.
The argument I'm giving NppExec is
python C:\Users\Sam\Desktop\Test.py
which is the filepath that NP++ gives me when I copy the full filepath to the clipboard.
Is there some configuration of NP++ that I have to set to get this to work?
I tried what you are attempting to do, and this is how I solved it:
Instead of passing the argument you gave, I passed this one:
C:\Python32\python.exe C:\Users\Sam\Desktop\Test.py for python 3+
C:\Python27\python.exe C:\Users\Sam\Desktop\Test.py for python 2
Generally, in order for it to work, you have to define where you have installed the python executable.
In general, you can use the following as an argument to NppExec for any currently opened Python script in Notepad++:
[Your Python install folder here]\python.exe "$(FULL_CURRENT_PATH)"
Note that "FULL_CURRENT_PATH" is a Notepad++ internal variable, not a placeholder for your file's actual path and filename, so the above argument should work without edits regardless of your current script's filename.
Further references for using NppExec with other source code: http://sourceforge.net/apps/mediawiki/notepad-plus/index.php?title=Compiling_Source_Code
This is an alternative method to running python programs in notepad++, which I recommend after being unable to find a suitable plugin.
create a batch file called pythonXX.bat ( where XX is the current version of python you're using ) and save it along side your python.exe in C:\PythonXX\
and insert this text into that batch file:
#ECHO OFF
C:\PythonXX\python.exe "%1"
PAUSE
#ECHO ON
Then inside notepad++ create a run command:
C:\PythonXX\pythonXX.bat "$(FULL_CURRENT_PATH)"
Then click save run and assign it to a keyboard short-cut, good to go :)

VirtualEnv initilaized from a bash script

I am trying to write what should be a super simple bash script. Basically activate a virtual env and than change to the working directory. A task i do a lot and condesing to one command just made sense.
Basically ...
#!/bin/bash
source /usr/local/turbogears/pps_beta/bin/activate
cd /usr/local/turbogears/pps_beta/src
However when it runs it just dumps back to the shell and i am still in the directory i ran the script from and the environment isn't activated.
All you need to do is to run your script with the source command. This is because the cd command is local to the shell that runs it. When you run a script directly, a new shell is executed which terminates when it reaches the script's end of file. By using the source command you tell the shell to directly execute the script's instructions.
The value of cd is local to the current script, which ends when you fall off the end of the file.
What you are trying to do is not "super simple" because you want to override this behavior.
Look at exec for replacing the current process with the process of your choice.
For feeding commands into an interactive Bash, look at the --rcfile option.
I imagine you wish your script to be dynamic, however, as a quick fix when working on a new system I create an alias.
begin i.e
the env is called 'py1' located at ~/envs/py1/ with a repository
location at ~/proj/py1/
alias py1='source ~/envs/py1/bin/activate; cd ~/proj/py1/;
end i.e
You can now access your project and virtualenv by typing py1 from anywhere in the CLI.
I know that this is no where near ideal, violates DRY, and many other programming concepts. It is just a quick and dirty way of getting your env and project accessible quickly without having to setup the variables.
I know that I'm late to the game here, but may I suggest using virtualenvwrapper? It provides a nice bash hook that appears to do exactly what you want.
Check out this tutorial: http://blog.fruiapps.com/2012/06/An-introductory-tutorial-to-python-virtualenv-and-virtualenvwrapper

Categories

Resources