Run python source file from PowerShell - python

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

Related

Trying to run Python program from command prompt

Path must be messed up and I can't fix it.
In the command prompt I am trying to open and run a python program that I made in IDLE. I am running Python 3.8.5. According to Automate the Boring Stuff, I should just be able to do:
py birthdays.py
But when I do that I get:
C:\Users\name\AppData\Local\Programs\Python\Python38-32\python.exe: can't open file 'birtdays.py': [Errno 2] No such file or directory
All of my scripts are located in: C:\Users\henri\AppData\Local\Programs\Python\Python38-32.
The only thing that I could think of is that it is going one step too far and searching in python.exe instead of just Python38-32. But Ii'm not even sure it works like that.
I tried to add the exact path using:
set PATH=%PATH%;C:\Users\name\AppData\Local\Programs\Python\Python38-32
But when I do this and press enter nothing happens.
when I want to use CMD to run python scripts, I just use
cd\
to back the main root of drive C. then use
cd folderAddress
for several time until to reach the exact scrip containing folder. Finally, I type
python scriptName.py
In your command prompt type python.The output should be python 3.** (depending on your python version).
If you see the python version it's working fine. In command prompt navigate to the folder that you have your python file using cmd command. then type
python birtdays.py
Don't forget the space after python.

Can't run Python file via Command Prompt, File is not defined error

I am new to Python and currently doing a basic python course to learn. I have been running code all day via the Command Prompt and it has been working fine. For some reason though it has stopped working and python files I try to run are returning the following error:
Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
As per the screen shot and the numbers on it, I performed the following steps in an attempt to run the file:
change to the folder where file is saved
run 'dir' to list all files. I am trying to run 'hello.py'. This contains the code: print('hello simon!')
I can run the file by just typing hello.py into the command prompt, this works ok
I can also run with: python hello.py - this works ok
when I activate Python by typing Python --> Enter, this starts the interpreter ok. However if I then try to run by typing hello.py I get the error message.
This has worked ok all day, I have not changed anything on my PC (to the best of my knowledge!) but just started to get this error a few hours ago. I have looked all over the internet for solution but found nothing. I have uninstalled and re-installed Python, restarted etc... all to no avail.
I am running Python 3.6.5 on a Windows 7 64 bit PC.
It won't let me attach a picture so here is link to screenshot of Command Prompt and error: https://i.stack.imgur.com/BBUe5.jpg
I hope someone can help me with this please
Thankyou
You are not supposed to execute hello.py in the Python Interpreter. It won't work. When you type in python and hit Enter in your Command Prompt, Just type this,
>>> print('hello simon!')
And hit Enter, it would definitely work. Because the interpreter is supposed to execute a code line by line. So if you want to run a Python Script then do not execute it in the Interpreter.
The problem is that when you write python (alone), the command line calls python shell and the following commands are run inside the python shell and not in the command line anymore. Calling a script from the shell has a different format (look it up). You can enter exit() to exit the shell back to command line again
What you are trying to achieve is you are running Hello.py inside Python.
Not with Python.
You need to run Hello.py with Python. As python is interpreter over here.
>>>python
means you are going inside python shell
>>>print('hello simon!')
Is equivalent to your program.
You are running your Python Script as you should and it's working. If you added Python to your path you can run Script you only need to call the Script "hello.py". If you have more than one intepreter, or you didn't added it to your path then you can call it like this "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" you can enven pass arguments to it "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" --argument
When you type python in a shell, then interactive mode is activated. This is like a shell where you type commands and got interpreted right away, in the same way as cmd and powershell works, but for python. This way you can test snippets, or just do simple stuff overly complicated like this
import os
ls = os.listdir(os.path.abspath('c:/'))
def print_dir():
for file in ls:
print(file)
Wich in cmd would be dir c:\ or in powershell ls c:\. The point is that you can test libraries, explore objects, replace the shell or just have fun.

File "<stdin>", line 1 in python 3.6 version [duplicate]

I am having trouble using the command line. I have a script test.py (which only contains print("Hello.")), and it is located in the map C:\Python27. In my system variables, I have specified python to be C:\Python27 (I have other versions of Python installed on my computer as well).
I thought this should be enough to run python test.py in the command line, but when I do so I get this:
File "<stdin>", line 1
python test.py
^
SyntaxError: invalid syntax
Looks like your problem is that you are trying to run python test.py from within the Python interpreter, which is why you're seeing that traceback.
Make sure you're out of the interpreter, then run the python test.py command from bash or command prompt or whatever.
Don't type python test.py from inside the Python interpreter. Type it at the command prompt, like so:
You can simply type exit() in the Python terminal to exit the Python interpreter. Then when you run the code, there will be no more errors.
I faced a similar problem, on my Windows computer, please do check that you have set the Environment Variables correctly.
To check that Environment variable is set correctly:
Open cmd.exe
Type Python and press return
(a) If it outputs the version of python then the environment variables are set correctly.
(b) If it outputs "no such program or file name" then your
environment variable are not set correctly.
To set environment variable:
goto Computer-> System Properties-> Advanced System Settings -> Set Environment Variables
Goto path in the system variables; append ;C:\Python27 in the end.
If you have correct variables already set; then you are calling the file inside the python interpreter.
In order to run scripts, you should write the "python test.py" command in the command prompt, and not within the python shell. also, the test.py file should be at the path you run from in the cli.
Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.
Come out of the "python interpreter."
Check out your PATH variable c:\python27
cd and your file location.
3.Now type Python yourfilename.py.
I hope this should work

Executing a python script from the terminal in Unix

I have a python script and I can't figure how to execute it in the terminal. The script has the #!/usr/bin/python at the beginning, is executable and I've tried locating myself in the right directory and python name.py but what I want to print (ergo what the script says it should print) doesn't print in the terminal.
I feel I'm missing something... I just started with this so... Help!
If name.py is executable, you can run it using:
./name.py
As for the #!, it is better to use as a first line:
#!/usr/bin/env python
This way path to python interpreter is not hardcoded, the first python found in $PATH is used instead.
Also: it makes your script to run in fresh environment (you can see man env for more information).

Python doesn't work properly when I execute a script after using Right Click >> Command Prompt Here

This is a weird bug. I know it's something funky going on with my PATH variable, but no idea how to fix it.
If I have a script C:\Test\test.py and I execute it from within IDLE, it works fine. If I open up Command Prompt using Run>>cmd.exe and navigate manually it works fine. But if I use Windows 7's convenient Right Click on folder >> Command Prompt Here then type test.py it fails with import errors.
I also cannot just type "python" to reach a python shell session if I use the latter method above.
Any ideas?
Edit: printing the python path for the command prompt that works yields the correct paths. Printing it on the non-working "Command prompt here" yields: Environment variable python not defined".
First of all, I work on Windows7 (among others) and running python from the command line works for me using "Command Prompt Here". Make sure you have the directory containing python.exe in your PATH environment variable, by running "Command Prompt Here" and running set.
Now for import errors. When importing, Python looks for modules in directories specified in the sys.path list. The PYTHONPATH environment variable is added to this list, along with some default directories, and the directory of the given Python script. However, in IDLE this directory is the directory of IDLE, so this could be causing the difference you are seeing when running things from IDLE compared to running them from the command line.
See http://docs.python.org/tutorial/modules.html#the-module-search-path for details.
Here is my advice on how to resolve this issue. You didn't mention what import errors you are recieving, but try running the script inside IDLE and checking the problematic modules' .__file__ attribute to see where they are. Then compare the sys.path from inside IDLE to sys.path you get when running Python from the command line. This should give you the information required to resolve your import errors.
I don't use Windows much, but maybe when you open Right Click -> Command Prompt, the PATH is different from navigate manually. First try to print your PATH (oh I have no ideal how to do this) and see if it different in 2 situation.
You can check the currently present enviroment variables with the "set" command on the command line. For python to work you need at least PYTHONPATH pointing to your python libs and the path to python.exe should be included in your PATH variable.

Categories