I recently installed both Python and Visual Studio Code. After taking an intro class I wrote a basic script and ran it in Visual Studio Code. That's when I noticed a problem with the way Python is setup in my Visual Studio code.
Problem:
When I start Visual Studio Code and open a python file, the Terminal defaults to "C:\Users\my_name\Documents Python" (this is the folder my python files are stored in). From what I understand, when you're in Python, the prompt should be ">>>". I am able to run my script but i cannot run any other Python code (ie something as simple as z = 5) in the terminal. If I type in "Python", I am prompted with ">>>" but can no longer run my script.
I thought this was an installation issue so i uninstalled and reinstalled both Python and Visual but the problem persists.
I tried adding the Python file path to where the program is installed to the windows environment under system settings and also clicked "Add to Path" when reinstalling Python but none of these solutions seemed to work.
when basic python code (ie z=5) doesn't seem to work but the script runs fine I get the error message below:
PS C:\Users\my_name\Documents\Python 2> z=5
z=5 : The term 'z=5' 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
+ z=5
+ ~~~
+ CategoryInfo : ObjectNotFound: (z=5:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Below is the error message I get after I switch to python and try running my script
PS C:\Users\my_name\Documents\Python 2> python
Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> & C:/Users/my_name/AppData/Local/Programs/Python/Python37-32/python.exe "c:/Users/my_name/Documents/Python 2/new2.py"
File "<stdin>", line 1
& C:/Users/my_name/AppData/Local/Programs/Python/Python37-32/python.exe "c:/Users/my_name/Documents/Python 2/new2.py"
^
SyntaxError: invalid syntax
>>>
There is nothing wrong with your setup. It looks you miss basic understanding of different ways to execute python code.
VS Code has integrated terminal. From there You can run your python script i.e. file with py extension same as you are on terminal/cmd/powershell. That is common way to write and execute code.
When you type python and hit enter you start python interactive shell. That is when you get >>> prompt. Your python interpreter evaluate and execute each line as you type in and hit enter. Same will happen if you type in python in cmd/powershell outside VS Code. Interactive mode is used more or less to experiment, test simple ideas, simple code examples, etc. but the code you type in is lost once you exit the interactive mode by >>>exit().
for further reference you may check
VSCode from start
How to execute python code
After reading the documentation above, I also had a similar problem after running scripts. I think that VSC is exiting out of python after running a script and requires starting up the python terminal again. I wonder if VSC can default to python after running a script instead of exiting out to powershell.
I figured out what the issue was here. Visual code thought Python was installed in the directory that my .py files are saved in as opposed to the actual location under program files. The path had to be edited under settings.
When you are in debug mode and stopped, you can type interactive Python in the 'Debug Window'. Useful for inspecting objects, variables, etc.
Otherwise as suggested, I just type "Python" in the terminal to get the interactive Python prompt ('>>>').
Related
I am trying to use Visual Code Studio for editing and running Python scripts for ABAQUS (finite element software using internal Python 2.7 interpreter with a lot of libraries).
The standard situation is that I run this command from Windows cmd prompt
abaqus cae noGUI="myscript.py"
==========================================================
EXPLANATION:
The command "abaqus" is a reference to this batch file
C:\SIMULIA\Commands\abaqus.bat
containing
#echo off
"C:\SIMULIA\Commands\abq2018.bat" %*
and the latter batch file abq2018.bat contains this
#echo off
setlocal
set ABA_COMMAND=%~nx0
set ABA_COMMAND_FULL=%~f0
"C:\SIMULIA\CAE\2018\win_b64\code\bin\ABQLauncher.exe" %*
endlocal
This is a standard configuration used for ABAQUS software.
==========================================================
Normally, I edit the Python scripts in PSPad and hit F9 which runs the edited script using the macro (therein called Highlighter)
"c:\SIMULIA\Commands\abaqus.bat" cae nogui="%File%"
and everything is perfect.
I tried to set up a similar "one click to run" scenario in Visual Studio Code by playing with "Workspace", "Interpreter", "launch.json" and "python.pythonPath" settings but without any success. The default Python interpreter 3.7 works normally for standard Hello-world etc. scripts.
My goal is to use the debugging features in Visual Studio Code...
Thanks for any help
Robert
Although the question is asked almost two years ago, if somebody is looking to use Visual Code Studio for editing and running Python scripts for ABAQUS, see pyabaqus.
Documentation:
https://pyabaqus.haiiliin.com/
Yes, I use it with VS Code and I am able to run it direcly from VSC. I have python 3.11 and installed pyabaqus package. You don’t tell VSC the location of abaqus instead you add the .bat file to path. The Pyabaqus finds the location of Abaqus. This package is not specific to VSC and python interpreter should work. I didn’t see any type hints tough.
From pyabaqus doc:
“
Setup your Abaqus Environment
In order to use Abaqus command to execute the Python script and submit the job, you need to tell pyabaqus where the Abaqus command is located. Usually, Abaqus command locates in a directory like this:
C:/SIMULIA/Commands/abaqus.bat
You can add the directory C:/SIMULIA/Commands to the system environment variable Path, or you can create a new system variable named ABAQUS_BAT_PATH, and set the value to the file path of the Abaqus command, i.e., C:/SIMULIA/Commands/abaqus.bat. “
I am trying to run the file created for Selenium using Command Prompt but I am unable to figure out what is the problem as I followed some of the solutions provided here and in Google as well but I am receiving the same error message.
When I am trying to run this code one by one: I can run it without any error and login successfully
Here is the code:
import selenium
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
baseurl = "http://www.gcrit.com/build3/admin/"
username = "admin"
password = "admin#123"
xpaths = {'usernameTxtBox': '//input[#name="username"]', 'passwordTxtBox': '//input[#name="password"]', 'loginButton': '//button[#id="tdb1"]'}
mydriver = webdriver.Chrome(executable_path=r"C:\mypath\Forselenium\chromedriver.exe")
mydriver.get(baseurl)
mydriver.find_element_by_xpath(xpaths['usernameTxtBox']).send_keys(username)
mydriver.find_element_by_xpath(xpaths['passwordTxtBox']).send_keys(password)
mydriver.find_element_by_xpath(xpaths['loginButton']).click()
I saved this in a .py file, and then added the extension of python37 in Environment variables "C:\mypath\Local\Programs\Python\Python37"
and added .py in the path as well.
My python file is saved in other file location. So I tried running the file in different ways
I ran in this way:
> C:\Users\mypath\Python37\python.exe "C:\Users\mypath\PythonScripts\SeleniumPractice.py"
I received this error message "SyntaxError: unexpected character after line continuation character"
Also, I tried to run in the way mentioned in this link how to run .py files in command prompt (Windows 7) but it is still not working properly.
I tried some of the solutions provided below as well but I am receiving error for some reason:
I changed the directory as well, but it is saying no such file but the file (SeleniumPractice.py) exists in this path.
C:\Users\Desktop\Learning\PythonScripts>py SeleniumPractice (tried using .py as well but receiving error like invalid syntax)
(null): can't open file 'SeleniumPractice': [Errno 2] No such file or directory
I tried using the other solution provided below as well, but receiving this error.
I am using this command C:\Users\>python SeleniumPractice.py "File
"SeleniumPractice.py", line 1 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27
2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 ^ SyntaxError:
invalid syntax"
Since I created scripts from IDLE, I had >>> on each line, which I replaced to blank and commented out any other rows generated from IDLE, and now I can run the script using the same solutions provided below python .py. Thank You Everyone
I think there's a difficulty with your question because you are giving a bundle of errors you are getting
Note that as you wrote:
I received this error message "SyntaxError: unexpected character after line continuation character"
We can assume that you actually CAN run .py files from the command prompt. You just have syntax error.
From reading your code, I see a redundant tab on the next to last line, that might give you the error.
2.You wrote
C:\Users\Desktop\Learning\PythonScripts>py SeleniumPractice (tried using .py as well but receiving error like invalid syntax)
(null): can't open file 'SeleniumPractice': [Errno 2] No such file or directory
Meaning you get a path error. It is also a python error saying to you that it can't find in the current path you are at (i.e. C:\Users\Desktop\Learning\PythonScripts) the file "SeleniumPractice". Is it really located there?
You wrote :
I am using this command C:\Users>python SeleniumPractice.py "File
"SeleniumPractice.py", line 1 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27
2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 ^ SyntaxError:
invalid syntax"
But we can't acutally know which Syntax Error you got. It only says you got a syntax error in line 1 of your code. Try maybe running it from IDLE and give us full description of your error?
And as written in one of the comments, pycharm might be really helpful for you understand better the mechanics of the errors you are getting. Or at list learn a little about how to work with Command Prompt, because, for example, if you install PATH correctly in environment variables, you don't need to write full path of you python.exe location, just need to write "python" and then the relative path of the file you are trying to run, and it will run beautifully.
go that location in your command prompt
then
python <filename.py>
you can check if python is being recognized as internal command by windows by simply executing the
python
command in your command prompt. it give an error then the environment variable setting is not correct
but usually that is not the case now with new version of python as it automatically ; i.e. at installation itself creates the entry.
You seem quite new to python I would recommend using an IDE like pycharm. It works like a charm
If you want to start running using command prompt, you might want to go to that directory where that file is, and type
python your_file.py
If you using Python 3.x you can change it to python3 instead.
you have SyntaxError in your code.
that mean your code have some bugs that forbid it from running
also you can run your code by:
python <path_to_code_file>
or
py -3 <path_to_code_file>
בהצלחה
I have a very simple program written but when I click start on the Visual Studio debugger nothing happens! Sorry total noob here. Working with python 3.6.5 32 bit for Windows. The program runs from the terminal just fine.
def main():
print ("hello world!")
if __name__ == "__main__":
main()
I've just come across the same issue in VS Code (I think) in that I can run a one line python file from the terminal and it will work as expected:
python HelloWorld.py
However when I try to run it in the debugger nothing happens other than the Debug toolbar briefly appearing. I got more suspicious having put a junk console entry in launch.json and it didn't cause any errors.
My problem was that the training instructions I'm following told me to set the following for my workspace settings so it would use the specific python executable in my virtual environment:
{
"python.pythonPath": "env\\Scripts\\python"
}
Once I changed the last part of that path to python.exe, everything worked as expected. Hopefully you can try a similar resolution in Visual Studio.
I had the same issue with all ide programs not just VS.code the problem is when installing python you didn't allow different ide environments to use python and its only executable from windows terminal what you need to do is delete python and VS code completely then again install python 3.x and in the first page of installation check the "Add python to path" box its a must if you want to use something other than windows terminal to code. after reinstalling the python now reset your device and install VS code again and that's it. problem solved
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
this is the first time I have used Python.
I downloaded the file ActivePython-2.7.1.4-win32-x86
and installed it on my computer; I'm using Win7.
So when I tried to run a python program, it appears and disappears very quickly. I don't have enough time to see anything on the screen. I just downloaded the file and double-cliked on it.
How do I launch this file? I know that it is a long file for a first Python tutorial.
Add the line
input()
to the end of the program, with the correct indentation. The issue is that after the data is printed to the console the program finishes, so the console goes away. input tells the program to wait for input, so the console won't be closed when it finishes printing.
I hope you're not using that program to learn Python; it's pretty complicated!
go to Start > All programs > Accessories and click on Command Prompt. then drag the python file from the explorer view into this command line and press Enter...
now you can watch the output of the script execution !
run it from a command prompt:
> python myscript.py
You can also start only the python interpreter from the command prompt (or by running python.exe) and then try some commands:
> python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>
>>> a = 2
>>> b = 7
>>> print a+b
9
>>>
Or run it from a batch file:
myprog.py
pause
Has the advantage that you can specify a different version of Python too.
Just a bit more on this.
You have a script myscript.py in a folder C:\myscripts. This is how to set up Windows 7 so that you can type > myscript into a CMD window and the script will run.
1) Set your PATH variable to include the Python Interpreter.
Control Panel > System and Security > System > Advanced Settings > Environment Variables. You can set either the System Variables or the User Variables. Scroll down till you find PATH, select it, click Edit.The Path appears selected in a new dialog. I always copy it into Notepad to edit it though all you need do is add ;C:\Python27 to the end of the list. Save this.
2) Set your PATH variable to include C:\myscripts
3) Set your PATHEXT variable to include ;.PY. (This is the bit that saves you from typing myscript.py)
This may now just work. Try opening a command window and typing myscript
But it may not. Windows can still mess you about. I had installed and then uninstalled a Python package and when I typed myscript Windows opened a box asking me which program to use. I browsed for C:\python27\python.exe and clicked that. Windows opened another command window ran the script and closed it before I could see what my script had done! To fix this when Windows opens its dialog select your Python and click the "Always do this" checkbox at the bottom. Then it doesn't open and close another window and things work as they should. Or they did for me.
Added: Above does not say how to pass arguments to your script. For this see answer Windows fails to pass arguments to python script