Starting Python tutorials but have some beginner questions - python

Hello I am attempting to learn Python using django in powershell on windows to create a simple CRUD app but have some questions regarding the setup and usage.
I have setup the path environment variable to include paths to a folder that includes test .py scripts that I thought allowed me to run directly from a c:\ in powershell but when I try to run the samples using:
c:\> python test1.py
c:\> python .\test1.py
It does not work and I get:
c:\Python27\python.exe: can't open file '.\test1.py':[Errno 2] No such file or directory
but if I CD to path first and run it works fine and I get the output in the powershell window itself:
c:\> cd c:\Python27\Scripts
c:\Python27\Scripts> python test1.py
In addition if I just type the name of the script from the root c:\ prompt such as:
c:\> c:\Python27\Scripts\test1.py
c:\> test1.py
it runs the script by opening in a dos box that that closes immediately since it ran the script and finished.
What is the difference between these methods and is there an issue running scripts one way or the other?

The issue here is that in the first case:
c:\> python test1.py
c:\> python .\test1.py
You're running python itself, and then the file is an argument to the interpreter. So python will be affected by PATH, but the file is relative. Both of these file paths mean to look for it in the same directory, which is the root of C:. Since the file isn't located there, the error results.
The second case:
c:\> c:\Python27\Scripts\test1.py
c:\> test1.py
It's the file itself being run as an "executable", factoring in PATH. On Unix, this would use the shebang and invoke the shell in pretty much the same way, however that's not the case on Windows. Instead, it's basically running whatever is associated with the .py extension at the OS level, which is likely to invoke a new Python interpreter in a new Window, hence the behavior where it disappears after it's done.
On Windows, since there's no shebang, I generally prefer to run the python interpreter directly and pass the script as an argument. I would generally switch to the directory the script is located in first. This way it's more shell-centric, and, I think, straightforward.
You can run pushd . to save the cwd, and then after popd to go back, optionally. That would work in .cmd files and similar, too.

Are you sure test1.py is in C: and not in c:\Python27\Scripts

Related

Automatically open a virtual environment when calling a python script in Windows

This question has been asked before, but the answers are all several years old and I could not get any to work for me, so I would appreciate some help.
The question is simple, really: I have a python script, and a virtual environment I want it to run in when I double-click it, or call it from another program. How can I achieve this?
you must add packages directory address to your sys.path
sys.path a built-in variable within the sys module. It contains a list of directories that the interpreter will search in for the required module.
add line below to top of your script, now you can double click on script file and every thing must work fine
import sys; sys.path.append("./<environment path>/Lib/site-packages")
this is simple solution however, as sinoroc said it's not good solution because in this situation you are using system interpreter not virtual environment interpreter so i wouldn't be surprised if things don't work as expected.
also you can download all packages that you need and extract them into single folder and add that folder to sys.path
first download packages you need with command below
pip download <package names> --dest <directory name>
for example:
pip download requests --dest packages
at the end add folder contain you packages to your path
import sys; sys.path.append("./<packages directory>")
Recommended Solution
the best solution is that write little batch script for windows or shell script for linux that automatically active virtual environment and then run your script
first create file with .bat extention for windows or .sh extension for linux and then add line below to it
for .bat file
<environment path>\Scripts\activate && python <script name>.py
for .sh file
source <environment path>/bin/activate && python <script name>.py
now you can click on this batch script *.bat file or shell script *.sh file and everything work's fine
Some ideas
Shebang
Place a shebang pointing to the Python interpreter inside the virtual environement with the full path at the top of the script.
#!/path/to/my/venv/bin/python
import sys
print(sys.executable)
Shell/batch script
Write a shell script wrapping the call to the actual Python script:
#!/usr/bin/env sh
/path/to/my/venv/bin/python /path/to/my/script.py
Python wrapper
#!/usr/bin/env python3
import subprocess
command = [
'/path/to/my/venv/bin/python',
'/path/to/my/script.py',
]
subprocesss.check_call(command)

Python script that can run from OSX Finder and Windows Explorer

I have a bunch of useful Python3 scripts that I use in different OS environments. They run fine when called from the terminal but I want to run them from both Windows Explorer and OSX Finder. In Windows, that is not an issue as the *.py files get associated with the installed interpreter.
For OSX, I am having some problems. I tried using the shebang line.
#!/usr/bin/python3
But Finder doesn't recognize it as a script. How do I make Finder recognize *.py files as scripts? I am interested in maximum portability with as few OS modifications as possible.
Also I explicitly specified the interpreter location above. It will be in different locations for different OSes. Is there a way to make it multi-OS so that if it doesn't find it in one location, it will try another? Say if I want to run it from one of Ubuntu's GUI File Manager.
EDIT: Here's more info on my use case. I want to go to a new computer and git clone my repo of Python3 scripts and be able to run them from within the GUI file manager with minimal changes to the new computer.
To make the script more portable use #!/usr/bin/env python3 as shebang. Side effect will be that it will run the first python3 interpreter it finds in the $PATH (Unix StackExchange question on that subject)
To run the script from the finder try to chmod the file. i.e.
chmod +x FILE
Found another possibility here: Link to the Blog
Make this the first line of your Python script "#!/usr/bin/env python"
Change the extension of the script file to ".command" i.e. my_python_script.command
In Terminal make the Python script file executable by running "chmod +x my_python_script.command"
Now when you double click the Python script in Finder it will open a terminal window and run.
Alternative I found would be this but it needs system modification: Superuser question

Running a python program in Windows?

I have Python 3.6 and Windows 7.
I am able to successfully start the python interpreter in interactive mode, which I have confirmed by going to cmd, and typing in python, so my computer knows how to find the interpreter.
I am confused however, as to how to access files from the interpreter. For example, I have a file called test.py (yes, I made sure the correct file extension was used).
However, I do not know how to access test.py from the interpreter. Let us say for the sake of argument that the test.py file has been stored in C:\ How then would I access test.py from the interpreter?
The simplest way would be to just do the following in cmd:
C:\path\to\file\test.py
Windows recognizes the file extension and runs it with Python.
Or you can change the directory to where the Python program/script is by using the cd command in the command prompt:
cd C:\path\to\file
Start Python in the terminal and import the script using the import function:
import test
You do not have to specify the .py file extension. The script will only run once per process so you'll need to use the reload function to run it after it's first import.
You can make python run the script from a specific directory:
python C:\path\to\file\test.py
In command prompt you need to navigate to the file location. In your case it is in C:\ drive, so type:
cd C:\
and then proceed to run your program:
python test.py
or you could do it in one line:
python C:\test.py
I may be misunderstanding what you are seeking, but I think what you are asking for is a IDE-like environment where you can load Python scripts, edit, and debug.
You already have IDLE, https://docs.python.org/3.6/library/idle.html, which came with the Python installation.
There are many IDEs available for Python. https://wiki.python.org/moin/IntegratedDevelopmentEnvironments Personally, I like using PyDev on Eclipse.

How do I run the python files from command shell/command prompt?

Really frustrated with this as one thing works at one time. Sometimes import filename.py works. But in the tutorials all I see is python filename.py. But when I try to give that, I am facing an error like invalid syntax.
I have edited all the environment variables and I have C:\Python27 folder in the same location. To be able to run the files using python filename.py what are the conditions that must be met? What should be the current working directory? Should the .py files be there in the same working directory?
import name is a python keyword for use within a python script and/or the python interactive interpreter (repl).
python filename.py is a shell command for use at a command prompt or within a shell script to run the python interpreter on a given python script file.
The working directory does not matter other than for whether the file listed in python filename.py can be found.
So for python filename.py to work you must be in the same directory as filename.py but you could just as readily use python c:\users\user\some\other\path\filename.py in which case the current directory isn't used to find the file.
If you get python syntax errors from attempting to run python on a python file that's a python error in the code and you will need to look at the python file to see what the error is.
Just to be clear, typing python filename.py only works from the Terminal (i.e. cmd.exe, Windows PowerShell, the "Terminal" application on a Linux kernel, etc.), not from the Python interpreter (i.e. python.exe), and only works if you have used the cd command to change into the directory in which the file is saved (so that the terminal knows where to look for filename.py). import filename can be used from the Python interpreter, but is not the ideal method as it creates a compiled version of filename.py and can only be used once (you would have to restart the interpreter to do so again). I'm not sure whether this works in the official Python distribution available from the Python website, but at least in the Anaconda distribution, you can run a file from the Python interpreter using runfile("C:/Users/CurrentUser/Subfolder/filename.py").

run python script directly from command line

#!/usr/bin/env python
I put that at the top of a script. I've seen that should make the script runnable from the command line without the need for python programname.py. Unless I'm misunderstanding I should be able to use programname.py as long as I have the above line at the top of the script. Is this correct?
It isn't working for me I just get an error indicating that I would have to use python at the beginning of the 'call'.
Universal running of Python scripts
You can pretty much universally run without the shebang (#!) with
python myscript.py
Or nearly equivalently (it places the current directory on your path and executes the module named myscript) (preferably do this!):
python -m myscript
from the command line, as long as you have Python installed and on your path environment variable (i.e. set to run with python, which, if installed, would typically be the case).
Shebangs (#!) are a Unix thing.
The shebang, as you're using it, is typically for running on a Unix platform (typically Apple or Linux). Windows would typically require cygwin to use the shebang.
You can usually default to whatever python is available on your system path with:
#!/usr/bin/env python
Assuming you're on a Unix, you might try other locations for your python setup, like:
#!/usr/bin/python
Muddling through
You can see what python you're currently using by using the unix which command, so if you want to see where your python is coming from, use this command:
which python
or on Windows (cygwin probably can run the shebang):
where python
On Linux/Unix, you'll need execution perms to run the file as well, in that manner. Use chmod
chmod +x myscript.py
(chmod also may apply to Cygwin in Windows)
If you're not running as root, you may require sudo, and that would be
sudo chmod +x myscript.py
And then attempt to run (within the same directory) with
./myscript.py
make the file executable
sudo chmod +x /path/to/file.py
and then from the same directory as file.py:
./file.py

Categories