Python script only working when ran in Visual Studio Code - python

My python code would only run if it was placed into Visual Studio Code. The code still works but when I click on the script to run it, it doesn't work, and when I use a command to run it, it doesn't work either.
# importing the module
import time
import wikipedia
import io
# looks for a random page and stores the topic in random
random = wikipedia.random(pages=1)
#searches for the topic and stores it in wiki
wiki = wikipedia.summary((random), sentences = 1)
# print the output of wiki
file = open("test.txt", "w")
file.write(wiki)
file.close
I also have an AutoHotkey script to run it but that doesn't work either.

That could mean that you don't have python added to path.
This is how you add python to path:
1. Start the Run box and enter sysdm.cpl
2. In the System Properties window go to the Advanced tab and
click the Environment Variables button
3. In the System variable window, find the Path variable and
click Edit
4. Position your cursor at the end of the Variable value line
and add the path to the python.exe file, preceeded with
the semicolon character (;)

Related

Unknown problem in Python. Printing does not work and files are not saved correctly

When I try to write something, such as variables, the code is renamed to the file name on the computer.
For example, if I write:
a = 20
f = 15
print(a+f)
then the code file will automatically be renamed to the first line, i.e. "a = 20"
Then, when I try to run the code, the program outputs nothing but "Python" and some incomprehensible words.
What could it be related to?
enter image description here
enter image description here
I installed the latest version of Visual Stuio Code with Python, they are new, so there should be no problems. But this time it went wrong.
After reinstalling the program, the problem remains.
First of all, if there is no special requirement, please do not use Code Runner to run the script, using the official extension Python is a better choice.
In addition, the dot on your file label means that you have not saved the file, you can add the following setting to enable automatic saving in the settings.
"files.autoSave": "afterDelay",
You may have created the file using the following method. File --> New File... --> Python File. At this time, the file has not been named, also not saved. You can see that there is no such file in the resource manager list at this time.
So the file label shows the first line of codes. This is a feature of vscode, you can refer to this link. And because the file has not been saved, there will be problems executing the script.
You can rename the script file directly (F2), or vscode will remind you to name the file when saving. Another way to create a file is to right click and choose New File..., enter filename and end with .py extension.

Refactor only selection black [duplicate]

We are not ready to automatically format the whole source code with black.
But from time to time I would like to execute black -S on a region via PyCharm.
There is a hint in the docs how to run black (or black -S (what I like)) on the whole file. But ...
How to run black only on a selected region?
Using Python Black on a code region in the PyCharm IDE can be done by implementing it as an external tool. Currently Black has two main options to choose the code to format
Run Black on the whole module specifying it on the CLI as the [SRC]...
Passing the code region as a string on the CLI using the -c, --code TEXT option.
The following implementation shows how to do this using the 2nd option. The reason is that applying Black to the whole module is likely to change the number of lines thus making the job of selecting the code region by choosing start and end line numbers more complicated.
Implementing the 1st option can be done, but it would require mapping the initial code region to the final code region after Black formats the entire module.
Lets take as example the following code that has a number of obvious PEP-8 violations (missing white-spaces and empty lines):
"""
long multi-line
comment
"""
def foo(token:int=None)->None:
a=token+1
class bar:
foo:int=None
def the_simple_test():
"""the_simple_test"""
pass
Step 1.
Using Black as an external tool in the IDE can be configured by going to File > Tools > External Tools and clicking the Add or Edit icons.
What is of interesst is passing the right Macros - (see point 3 "Parameter with macros") from the PyCharm IDE to the custom script that calls Black and does the necessary processing. Namely you'll need the Macros
FilePath - File Path
SelectionStartLine - Selected text start line number
SelectionEndLine - Select text end line number
PyInterpreterDirectory - The directory containing the Python interpreter selected for the project
But from time to time I would like to execute black -S on a region via PyCharm.
Any additional Black CLI options you want to pass as arguments are best placed at the end of the parameter list.
Since you may have Black installed on a specific venv, the example also uses the PyInterpreterDirectory macro.
The screenshot illustrates the above:
Step 2.
You'll need to implement a script to call Black and interface with the IDE. The following is a working example. It should be noted:
Four lines are OS/shell specific as commented (it should be trivial to adapt them to your environment).
Some details could be further tweaked, for purpose of example the implementation makes simplistic choices.
import os
import pathlib
import tempfile
import subprocess
import sys
def region_to_str(file_path: pathlib.Path, start_line: int, end_line: int) -> str:
file = open(file_path)
str_build = list()
for line_number, line in enumerate(file, start=1):
if line_number > end_line:
break
elif line_number < start_line:
continue
else:
str_build.append(line)
return "".join(str_build)
def black_to_clipboard(py_interpeter, black_cli_options, code_region_str):
py_interpreter_path = pathlib.Path(py_interpeter) / "python.exe" # OS specific, .exe for Windows.
proc = subprocess.Popen([py_interpreter_path, "-m", "black", *black_cli_options,
"-c", code_region_str], stdout=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
# By default Black outputs binary, decodes to default Python module utf-8 encoding.
result = outs.decode('utf-8').replace('\r','') # OS specific, remove \r from \n\r Windows new-line.
tmp_dir_name = tempfile.gettempdir()
tmp_file = tempfile.gettempdir() + "\\__run_black_tmp.txt" # OS specific, escaped path separator.
with open(tmp_file, mode='w+', encoding='utf-8', errors='strict') as out_file:
out_file.write(result + '\n')
command = 'clip < ' + str(tmp_file) # OS specific, send result to clipboard for copy-paste.
os.system(command)
def main(argv: list[str] = sys.argv[1:]) -> int:
"""External tool script to run black on a code region.
Args:
argv[0] (str): Path to module containing code region.
argv[1] (str): Code region start line.
argv[2] (str): Code region end line.
argv[3] (str): Path to venv /Scripts directory.
argv[4:] (str): Black CLI options.
"""
# print(argv)
lines_as_str = region_to_str(argv[0], int(argv[1]), int(argv[2]))
black_to_clipboard(argv[3], argv[4:], lines_as_str)
if __name__ == "__main__":
main(sys.argv[1:])
Step 3.
The hard part is done. Lets use the new functionality.
Normally select the lines you want as your code region in the editor. This has to be emphasized because the previous SelectionStartLine and SelectionEndLine macros need the selection to work. (See the next screenshot).
Step 4.
Run the external tool previously implemented. This can be done by right clicking in the editor and choosing External Tools > the_name_of_your_external_tool.
Step 5.
Simply paste (the screenshot shows the result after running the external tool and pressing Ctrl + v). The implementation in Step 2 copies Black's output to your OS's clipboard, this seemed like the preferable solution since this way you change the file inside the editor thus Undo Ctrl + z will also work. Changing the file by overwrite it programmatically outside the editor would be less seamless and might require refreshing it inside the editor.
Step 6.
You can record a macro of the previous steps and associate it with a keyboard shortcut to have the above functionality in one keystroke (similar to copy-paste Ctrl + c + Ctrl + v).
End Notes.
If you need to debug the functionality in Step 2 a Run Configuration can also be configured using the same macros the external tool configuration did.
It's important to notice when using the clipboard that character encodings can change across the layers. I decided to use clip and read into it directly from a temporary file, this was to avoid passing the code string to Black on the command line because the CMD Windows encoding is not UTF-8 by default. (For Linux users this should be simpler but can depend on your system settings.)
One important note is that you can choose a code region without the broader context of its indentation level. Meaning, for example, if you only choose 2 methods inside a class they will be passed to Black and formatted with the indentation level of module level functions. This shouldn't be a problem if you are careful to select code regions with their proper scope. This could also easily be solved by passing the additional macro SelectionStartColumn - Select text start column number from Step 1 and prepending that number of whitespaces to each line in the Step 2 script. (Ideally such functionality would be implemented by Black as a CLI option.) In any case, if needed, using Tab to put the region in its proper indentation level is easy enough.
The main topic of the question is how to integrating Black with the PyCharm IDE for a code region, so demonstrating the 2nd option should be enough to address the problem because the 1st option would, for the most part, only add implementation specific complexity. (The answer is long enough as it is. The specifics of implementing the 1st option would make a good Feature/Pull Request for the Black project.)
I have researched about this because it actually looks interesting, and I've came to the conclusion that you can maybe use:
black -S and_your_file_path
or:
black -c and_a_string
to format the code passed in as a string.
I will also follow this thread because it looks interesting.
And I'm also going to do more research on this and if I find something I will let you know.

PYTHON AND BATCH SCRIPT: Run file if it exists and create if it doesn't

Full Disclaimer: I DO NOT KNOW PYTHON.
Hi Guys,
I have made an AutoHotKey Script for my volume keys. I would like to create a batch file which runs a python file (so if I change computers, I can easily create this scripts) which would do the following
Check if volume_keys.ahk exists in the D Drive
If it exists, run that;
If it doesn't exist, then create a file named volume_keys.ahk and add my script to it.
My script is:
^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down}
I know how to code the .bat file and just need help for the python point-of-view, but I request the community to check it:
#ECHO OFF
ECHO This script will run an AHK Script. If you want to stop this process from happening, then cross this window off.If you want to continye:
pause
cd d:
D:\run_volume_keys_ahk_script.py
I really appreciate any help by the community.
Thanks in advance
You can use the os library for this. Here's what the python program would look like.
import os
if os.path.isfile('D:\\volume_keys.ahk'): # check if it exists
os.system('D:\\volume_keys.ahk') # execute it
else:
with open('D:\\volume_keys.ahk', 'w') as f: # open it in w (write) mode
f.write('^!NumpadMult::Send {Volume_Mute} \
^!NumpadAdd::Send {Volume_Up} \
^!NumpadSub::Send {Volume_Down}') # Write to file
os.system('D:\\volume_keys.ahk') # execute
To activate the ahk script, you might want to use the subprocess module, of which I took the example from here
import subprocess
subprocess.call(["path/to/ahk.exe", "script.ahk"])
Note that you'll have to find the ahk executable on a computer before you can use the script, maybe you want to automatically check that too.
You can set the path you want to check for scripts in one string, and then add the filenames of your scripts as strings to a list. You can use listdir() from the os module to see any files and directories at a given path, then iterate over your scriptnames and check if it exists in that list of files. If it does, run it.
In this example I copy-pasted your script into a string as value for the key 'scriptname' in a dictionary, so that python can actually create the script file. This isn't really a neat way to do it though, you might want to have your scripts prepared in a directory next to your python script and copy them from there. See an example of how here
from os import listdir
from os.path import isfile, join
CHECK_PATH = "D:"
AHK_EXECUTABLE_PATH = "path/to/ahk.exe"
SCRIPTS_TO_CHECK = {'script1.ahk':"""^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down} """, 'script2.ahk':" some other script here"}
files_to_check = set(listdir(CHECK_PATH)) # using a set for fast lookup later
for scriptname, script in SCRIPTS_TO_CHECK.items():
if not scriptname in files_to_check:
print(f"script {scriptname} not found, creating it.")
with open(scriptname, 'w') as file:
file.write(script)
# else
subprocess.call(AHK_EXECUTABLE_PATH, scriptname)

Python 3 from CMD

I am attempting to run this .PY file from Command Prompt:
# Merge two .BSG files
# Starting block and world position are taken from the first file
# Example: "bsgmerge input.bsg output.bsg merged.bsg"
import io, sys
one = open(sys.argv[1]).readlines()
two = open(sys.argv[2]).readlines()
for n in [1,3,5,7,9,11,17,19,21,23]:
one[n] = one[n][:-1]+"|"+two[n].partition("|")[2]
open(sys.argv[3],"w").write("".join(one))
It is a program that takes a creation from the game Beseige and merges it with another saved creation so that opening the merged file results in both creations being present. If you want more details, you can read up on that here.
I am having trouble figuring out how to call this program from the command line. At first I thought the problem was me having Python 2 (it requires Python 3), so I uninstalled 2 and installed 3. This did not help.
What I am doing is entering the "python" command to pull up the Python environment within CMD, then entering the command to call the program based on the third comment in the file ("bsgmerge input.bsg output.bsg merged.bsg").
I tried using full file paths or simply changing to the correct directory before typing the "python" command and using only the file names, but so far I've had no luck.
When I am in the correct directory, then enter the Python environment, typing the command "bsgmerge 1.bsg 2.bsg M.bsg" (my existing files to be merged are 1.bsg and 2.bsg), this error occurs:
File "<stdin>", line 1
bsgmerge 1.bsg 2.bsg M.bsg
^
SyntaxError: invalid syntax
I took a Python course (which is why I used to have Python 2 on my machine) last fall, so I noticed that there is no "def" defining a function in the above code, which is something I've never encountered, so I'm thinking that is the root of my problems.
Thanks in advance for the help.
I was probably same problem with python launcher.
If you use Linux, first line shoud be:
#! /path/to/your/python/3
In Windows it some more complicated:
In registry by regedit change
HKEY_CLASSES_ROOT\Python.File\shell\open\command from "C:\Python27\python.exe" "%1" %* to "C:\Windows\py.exe" "%1" %*.
And first line of script shoud be:
#! python3
Now it shoud work properly.

How to use the Windows Explorer or Finder file dialogues in Tkinter/Python2.7.3?

Among other things, I am currently trying to create a basic text editor which can open text files, edit them, and then save them. I have used this Tkinter dialogue for the GUI 'file manager,' but I was wondering if anyone knew the way to access the one that comes default on Windows?
Thanks!
Technical Things:
OS: Windows 7
Language: Python 2.7.3
EDIT 1
By the DEFAULT file dialogue, I mean the windows explorer dialogue:
I also use mac. Assuming that my application is cross-platform, would there be any way for me to have the program check what the os was, and then open either Finder or Windows Explorer.
I need the program to be able to save and open items in different commands. How would I do this?
It's not exactly clear what you're asking, since the one that tkinter comes with is default in Windows. Here's another link for that, just in case you got mixed up somewhere along the line. Remember that you can set it so it only finds a certain type of file, starts in a specific place, returns the filename or directory, or even open the file (I think)
If you mean the Windows Explorer you can open it and close it with pywin32, but not much else. Taken from this answer
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
try importing tkFileDialog:
import tkFileDialog as tkfd
def save():
savenm = tkfd.asksaveasfile()
f = open(savenm.name,"w")
# then put what to do with the opened file
def open():
opennm = tkfd.askopenfile()
f = open(savenm.name,"r")
# then put what to do with the opened file
then make a button that uses the functions:
import Tkinter as tk
root=tk.Tk()
SAVELOADFRAME = tk.Frame(root)
SAVELOADFRAME.pack()
savebtn = Button(SAVELOADFRAME,text="Save",command=save)
savebtn.pack(side=LEFT)
root.mainloop()
loadbtn = Button(SAVELOADFRAME,text="Open",command=open)
loadbtn.pack(side=RIGHT)
maybe if you have a notepad box you might want to insert the text from the file into the tk.Text widget. The above code only works for text based files really (e.g. *.js, *.txt, *.py) not *.exe, *.dll, etcetera.
hope that solves your problem :^)

Categories