Python doesn't run properly on Visual Studio Code - python

I downloaded Visual Studio Code and installed Python following the instructions at https://code.visualstudio.com/docs/python/python-tutorial.
As I chose the Python extension in Visual Studio Code, an installation started, but it told me afterwards that the system install is not supported. Therefore I installed it with Homebrew.
First of all, I seem do not have the green 'run'-button displayed in the installation tutorial above. There I only can run code with right click and 'Run Selection/Line in Python Terminal'.
A simple print('Hello, World!') seems to run properly, but when I try to run a program with more than one line (i.e., more than one instruction) I get multiple error messages that I did not get while using Anaconda before.
For context: I am currently learning to program using Python and follow the book 'Automate the boring stuff with Python'.
The code I try to run is:
#! python3
# mclip.py - A multi-clipboard program.
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""", 'upsell': """Would you consider making this a monthly donation?"""}
import sys, pyperclip
if len(sys.argv) < 2:
print('Usage: py mclip.py [keyphrase] - copy phrase text')
sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
pyperclip.copy(TEXT[keyphrase])
print('Text for ' + keyphrase + ' copied to clipboard.')
else:
print('There is no text for ' + keyphrase)
For clarification:
Traceback (most recent call last): File "/Users/XXX/Desktop/Python Projects/Ex.py", line 7, in <module> import sys, pyperclip ModuleNotFoundError: No module named 'pyperclip'
is the error I get.
I just want to use Visual Studio Code properly and I am really not sure why it isn't working or what I did wrong while installing it. (For example, why am I missing the green 'run'-button?!)

There is one syntax error in your code on line 10. sys.exit() should be on the next line. Once that was fixed, it ran fine for me in my Visual Studio Code.

It's the indentation error:
if len(sys.argv) < 2:
print('Usage: py mclip.py [keyphrase] - copy phrase text')
sys.exit()
sys.exit() should be on the next line.

For displaying a green play button, you have to install the Python extension in Visual Studio Code.
You have made an error. When I ran it I got it. You have to place sys.exit() after enter or on the next line:
sys.exit()

Related

Pycharm does no read python file without error

When I create a project and I run the script which should print something but I got nothing:
C:\Users\mahfo\AppData\Local\Programs\Python\Python38-32\python.exe C:/Users/mahfo/PycharmProjects/pythonProject1/main.py
Process finished with exit code 0
main.py file content:
print('wef')
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
When I check: sys.prefix == sys.base_prefix, output is: True,
and sys.prefix output:
'C:\\Users\\mahfo\\AppData\\Local\\Programs\\Python\\Python38-32'
It is the first time I try on Windows. Do you know why this happens, please? Any help is appreciated.
Edit:
I've tried to run the file directly from the command prompt and it run correctly with python but not python3. So Pycharm does not recognize the file (without error) because the file can be read only with python2. I don't understand why because the pycharm environment setting are on python3.
Edit 2:
I had Python 2.7 installed that i have deleted.
Pycharm is still not printing when I run but it print on debug console. I really don't understand why.

Neovim throws an error running input(), runs ok in Vim

Noob question here, Neovim throws an error when running a script using input() in the command-line window, while the same script runs in vim 8.0. eg
print('Enter your name:')
myName = input()
:! python % <- ex command used
Nvim output:
myName: Traceback (most recent call last):
File "x.py", line 2, in <module>
myName = input()
EOFError: EOF when reading a line
shell returned 1
I prefer the way neovim runs it's scripts in it's own bottom window as opposed to vim outputting to the command line, but I have to switch to vim for any scripts using input().
Is there a nvim.init setting or a different command I can use to succeed here, or is this a known flaw in neovim? I'm on wsl using the latest vim and nvim.
I am not sure why you're getting this error. But, since you are using neovim, have you tried using the built-in terminal emulator? The below command can be used to run the program within newovim in a new split window:
:vsplit term://python3 %
python3 is the name of program, which can be substituted with any other program. Where % is the current file's path. See :h terminal-start for more information.
The same can be done using Vim (8.0 or above) by using the command:
:term python3 %
this will again open a new split for the program running. See :h terminal for more information.
A further optimization to the workflow would be to add a filetype specific mapping. In our case that would be(unix like systems) in ~/.vim/after/ftplugin/python.vim
nnoremap <leader>r :vsplit term://python3 %<cr>

Python script doesn't print output in command prompt

I need some advice with a Python script. I'm still new and learned it by myself. I found the script on Google. After I retype it, it doesn't print the result in the console. How can the result of the script be shown in the console? Details as below:
C:\Python27>test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d
C:\Python27>
After I press enter, nothing happens. Should the result be shown or not?
Here's the code that I retyped:
#!/usr/bin/python
#coding: ascii
import requests
import sys
import re
url = 'http://hashtoolkit.com/reverse-hash?hash='
try:
hash = sys.argv[1]
except:
print ("usage: python "+sys.argv[0]+" hash")
sys.exit()
http = request.get(url+hash)
content = http.content
cracked = re.findall("<span title=\*decrypted (md5|sha1|sha384|sha512) hash\*>(.*)</span>", content) # expression regular
print ("\n\tAlgoritmo: "+cracked[0][0])
print ("\tPassword Cracked: "+cracked[0][1])
The first line in your script is called a Shebang line.
A Shebang line tells the script to run the Python interpreter from that location.
The shebang line you provided is a Linux system path, but it looks from the path you are executing Python from, that you are running on Windows.
You can do one of two things here to fix that:
Remove the Shebange Line.
Remove the first line from your script.
Execute the script using python test1.py COMMAND_LINE_ARGUMENTS
Modify Your Shebang line.
Change the first line of your script from !/usr/bin/python to
#!python (This is assuming that python is in your systems PATH variable.)`
Execute the script using test1.py COMMAND_LINE_ARGUMENTS
Also, you are trying to import the requests module that is not installed in the standard library.
If you haven't installed this yet, you can do so by going to your Python install directory and go to the scripts folder.
Hold shift and right click and go Open command window here
Type pip install requests and hit enter.
After that you should be good to go, execute the script by navigating to it and type test.py COMMAND_LINE_ARGUMENT
If a Python script doesn't have the shebang line:
python test.py COMMAND_LINE_ARGUMENT
you need to run your script using python. try:
C:\Python27>python test1.py af8978b1797b72acfff9595a5a2a373ec3d9106d

NameError when using input() with Python 3.4

I am a new Python user and I have been working through a number of tutorials. This has included running some of the code from the Command Prompt. This worked fine when I first tested the code but for some reason it seems to have stopped working and I am now getting errors when using Input(). I have included the code below and the error message I am receiving.
Code:
import sys
print (sys.version)
print("hello world")
myName = input("What is your name?")
print(myName)
if (myName == "Matt"):
print("Matt is great!")
elif (myName == "Bob"):
print("Bob is ok")
else:
print("Hello world")
input("Press enter to continue")
Error Message:
C:\Users\matt.xxxx>cd C:\Python34\Scripts\Projects
C:\Python34\Scripts\Projects>helloworld.py
2.7.7 (default, Jun 1 2014, 14:21:57) [MSC v.1500 64 bit (AMD64)]
hello world
What is your name?Matt
Traceback (most recent call last):
File "C:\Python34\Scripts\Projects\helloworld.py", line 6, in <module>
myName = input("What is your name?")
File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined
C:\Python34\Scripts\Projects>
I know this can occur when using older versions of python, however I have checked and I am fairly sure I am using version 3.4 (checked using import sys etc.). I have recently installed PyCharm which is the only thing I can think of that has changed. The code works in PyCharm and from IDLE but not from the Command Prompt. Any help would be much appreciated.
From your example , I believe you are running the script using - helloworld.py - this would cause Windows to lookup the default application associated with the extension .py and run it.
I am guessing in your case when you installed PyCharm, it somehow made Python 2.7.7 the default application for .py files (Or it was like that from the start) so when you directly run .py files (even from command prompt) they run using Python 2.7.7 .
You said in your comment that when running python directly from command prompt, you are getting python 3.4 , so the easiest way to fix your issue would be to use that to run your script.
Run it using the command -
python helloworld.py
As a long term solution, you may want to consider changing the default application associated with .py files. You can checkout this link for guide on how to do that

Error after running mapper.py locally in terminal

I have just started learning Hadoop. I tried to run a simple mapreduce job on it, but before that I tried to check it locally. But its returning error. Kindly suggest any solution to it. I am using Ubuntu 12.04 LTS.
SO the code is written in gedit, and is ad follows.
import sys
for line in sys.stdin:
line = line.strip()
words = line.split()
for word in words:
print '%s\t%s' %(word,1)
Then I write the below command in terminal to check if mapper is working fine
maitreyee#bharti-desktop:~$ echo "foo faa" | /home/maitreyee/Documents/mapper.py
and the terminal returns the following error:
/home/maitreyee/Documents/mapper.py: line 1: import: command not found
/home/maitreyee/Documents/mapper.py: line 5: syntax error near unexpected token `line'
/home/maitreyee/Documents/mapper.py: line 5: `line = line.strip()'
You are missing the shebang line at the top of your script. Add something like this (whichever python makes sense for your machine):
#!/usr/bin/python
Here I use the system python under /usr/bin/python
The shebang line is needed because you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH.
If you want more to know about writing map reduce code in python, you can follow this
tutorial!

Categories