Running Python Scripts from Anywhere - python

I'm new to programming. Giving this another try.
I've been able to make Python run from PowerShell through changing the Environment variables. When I try to launch Python using Win + R, only py launches python. This puzzles me. PowerShell and cmd have no problem with just typing python.
I'm also trying to make it so that I can launch a python script from anywhere. I made a simple script called again.py in visual studio code and saved the script in a specific folder. When I try to run the script in VSC, I always get the error:
[Running] python -u "c:\Users\xyz\Programming\Python\again.py"
'python' is not recognized as an internal or external command,
operable program or batch file.
[Done] exited with code=1 in 0.137 seconds
By my understanding, if a folder is included in Path, and a file is called that is stored within that folder, the file/script should run. I should be able to call that file from anywhere, but I am just not able to type the file name in PowerShell or Run and have it run.
win + R returns:
Windows cannot find 'again.py'. Make sure you type the name correctly, and try again.
PowerShell: start again.py
start : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:1
+ start again.py
+ ~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
Typing again.py into cmd causes it to run just fine.

The Powershell error is caused by a space in the file name. Powershell looks at input, start again.py, and parses it like so
first token on row is word "start"
start is an alias to start-process
second token on row is "again.py"
that will be passed as argument to start-process
The easiest work-around is to avoid spaces in file names. Use an underscore or camel case instead. That is, startAgain.py or start_again.py. One can use spaces, but there are extra quoting tricks involved. What's worse, those depend on shell. Cmd has its own rules, Powershell has very different ones. Since you are learning how to program, consider focusing on Python for now and worry later on shell quoting issues.

Related

why the same powershell command run on the powershell console but not using os.system?

I would like to include a command to create a 7zip archive withinin a Python script. Since I am working on Windows, I need to pass the command to the powershell console. I am planning to do it with os.system (I am aware that this is not the best way to do it and that I should use subprocess, but I really just need a quick fix and it would not be time effective for me to learn to use a new module in this context).
The following command works if run from the powershell console
&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch
So I recreate the same string within python like this:
cmdl = r"&'C:\\Program Files\\7-Zip\\7z' a -mx=0 X:/myarch.zip X:/myarch"
The string is interpreted as follow:
"&'C:\\\\Program Files\\\\7-Zip\\\\7z' a -mx=0 X:/myarch.zip X:/myarch"
Now, if I copy-paste the above string within the powershell console, it runs without problems. However, if I run it within python using os.system(cmdl) I got the following error
"The filename, directory name, or volume label syntax is incorrect"
Why is this the case and how can I fix this issue ?
os.system is meant for executing cmd commands, cmd commands can be ran in powershell maybe after all powershell is a bit advanced but I'm sure that you can't run a cmd command in powershell, henceforth your code is not working.
However a creative solution for executing a powershell command from python(not using python) would be to write your command into a .ps file(powershell script)and then run it using os.startfile()(use this code: os.startfile("script.ps"))

Visual Studio Code Terminal

When I try to run Python code in the terminal with a print command, nothing happens. When I try the test.py command in the terminal itself, the text copied below is what gets output.
Please assist in how to get the terminal to print my code.
E:\Kath\Documents\blockchain> test.py
test.py : The term 'test.py' is not
recognized as the name of a cmdlet, function,
script file, or operable program. Check the
spelling of the name, or if a path was
included, verify that the path is correct and
try again.
At line:1 char:1
+ test.py
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound:
(test.py:String) [], CommandNotFoundExce
ption
+ FullyQualifiedErrorId : CommandNotFound
Exception
Once you open the VS Code, select a Python 3 interpreter by opening the Command Palette (Ctrl+Shift+P), start typing the Python: Select Interpreter command to search, then select the command.
You can also use the Select Python Environment option on the Status Bar if available.
Now, create a new file, and save it with the extension .py. Once done this, write the required code in the workspace. And then Right Click on the workspace -->Run Python file in the terminal.
This runs the selected file.
Hope this solution helps.
In "Terminal" you get what is essentially a regular Command prompt, and command interpreter in your case is PowerShell.
So, to execute the python script you should run it as:
python test.py
or
python3 test.py
or similar, depending of your python executable.
As Powershell is your default command shell in Visual Studio Code, if the ".py" extension is registered with Python, you can try:
.\test.py
If you use virtual environments, make sure you select the correct Python interpreter.

How do I keep a console window open after my python program terminates to see any errors produced?

I am using python 3 on Win10 and running my code by opening a Command Prompt window and typing the file location. However, the window closes as soon as the program terminates, and before I can read any errors.
Edit: This happens whether or not the program has errors.
Thank you.
Solution 1:
I just saw your comment:
When I do that, I recieve the error 'python' is not recognized as an
internal or external command, operable program or batch file
It looks like you haven't specified the path to the python executable: you need to add the python executable path to your Window's PATH variable. You can see how to do that here: Add Python to the PATH Environmental Variable (‘python’ is not recognized as an internal or external command)
Solution 2:
You can use input("enter to exit") at the end of your python code to keep the program alive. It would exit once you press enter.
You could also surround your code in a try except statement and place thr input() in the except to prevent the program from exiting when there are errors, but like #Kevin mentioned in the comments, this would catch run time errors but not syntax errors.
Solution 3:
You can write errors or anything information you want to a file such as log.txt for example, and then read that log file once the code finishes running e.g. how to write to a file in Python
FWIW, I have several Python versions on my Windows system, so I don't want to add any Python directories to my path permanently.
Code for each version is in a separate folder (e.g. 'py37'), with a subfolder for each project e.g. 'myProject'.
In py37, there's a batch file called pyEnv.bat with this content:
#echo off
path=%path%;C:\Python37\;C:\Python37\Scripts\
cd.
cmd
In Windows explorer, I head over to the project folder I want to work in, click in the address bar and type ..\pyEnv. That launches a DOS-box, in which I now can do python myproject.py. You can see print() output, errors, and so on.
You can up-arrow to try different modules, having typed them first.
Once you quit the DOS-box, your path is back to normal again.

running a python script as a command line variable

I am new to python and wanted to make a simple script that acted like the ls command in a mac/linux terminal but for cmd in windows. The code itself works and if I run the script using python ls_script.py in my cmd it works fine. However, I want to make it so that I can run it in any active directory by just typing in ls in my cmd. I made an environment variable in cmd called ls that has a value of python ....\ls_script.py, which assumed would work since if i were to type that exact thing in manually, it works. However, when I just type in ls, it gives the following error:
"'ls' is not recognized as an internal or external command, operable program, or batch file."
I don't think your problem has anything to do with python, considering that the python script does what you want. The problem is getting the environment variable to work, right?
I believe this question has the answer you're looking for:
How to create ls in windows command prompt?
In short, it looks to me like the way to achieve what you wanted was to not use environment variables, but to create a batch file instead.

Run python source file from PowerShell

I'm trying to learn python but have some problem running source files from power shell. When I type 'python' it opens up and I can type python commands directly in the shell. I think this is called interactive mode. But when I try to run/execute a source file I get an error message: It sayys: Syntax error: invalid syntax.
I use 'python myfile.py' when I try to execute the script.
If I run the same file from IDLE it works just fine. Ana idea what I'm doing wrong?
Here is myfile.py. I'm running python 2.7
# filename: myfile.py
while True:
s = raw_input('Enter something: ')
if s == 'Quit':
break
print 'Lenght of the string is', len(s)
print 'Done'
You might have more than one version of Python installed and the version IDLE is using is newer. To see what version of python you have you can type >python -V at a command line. If that version looks appropriate then you might need the full path to the file as the second parameter. E.g >python C:\myfile.py.
If you installed Python correctly there is always a chance that just typing the name of the script will run it with python. E.g. >myfile.py
I always find that adding C:\Python27 to the %PATH% variable and .PY to the %PATHEXT% variable makes running scripts easier. In this case just >myfile should work.
Edit after Update:
Typing just >python with no parameters opens python in 'interactive mode' which is different from the batch or scripting mode that your script is intended for. If executed with arguments the first argument is taken as the file path and further arguments are passed to the script in the sys.argv list.
You will need to put the full path of the Python executable within the command line in order for it to work. You could check and ensure that your python exe is included in your Path among your system variables.
Disclaimer: I don't know PowerShell, but I do know cmd.exe.
I don't know why python myfile.py doesn't work, but assuming that PowerShell bears at least some similarity to cmd.exe, the following should probably work: myfile.py. That's right, just enter the name of the Python script and hit enter.
If you started by typing "python" in powershell you will need to get out of that script.
If you are in python type:
quit()
then type
python myfile.py
This should work if your python is installed correctly.
Try to type this in Powershell:
$env:path="$env:Path;C:\Python33
After this, command
python yourfile.py
should work.
This my sound silly, especially coming from a beginner.
Just save the file on your desktop. Open up powershell and drag the file directly into powershell and it opens. kind of tedious but it works

Categories