I would like to print the path and file name of my python code.
For example, " my_directory/my_subdirectory/my_python_code_name "
I tried different things, like import sys, os
followed by any of those below:
sys.argv[0]
print('sys.argv[0] =', sys.argv[0])
print('full path =', os.path.abspath(pathname))
os.path.realpath(__file__)
None of those works.
I am using spyder.
I'm not sure if this is late, but maybe this answer can help someone else. In general in order to get a file path you would do something like this:
import os
print('Full path:', __file__)
print('Full path without file name:', os.getcwd())
print('Name of the file:', os.path.basename(__file__))
However using __file__ may not work for you if you are using an interactive prompt as the prompt from Spyder or Jupyter Notebook.
In this latter case you could write in a cell the following:
%%javascript
IPython.notebook.kernel.execute('notebook_name = "' + IPython.notebook.notebook_name + '"')
With this you are defining the variable notebook_name with the name of the .ipynb file from which you are executing.
To better answer the question, in Spyder you can execute code from a temp python file which works exactly as a normal python script, and for which you can use the first fragment of code above.
From your answers however I understand that you are executing code from the Spyder IPython Console that doesn't really have a name of a file to display. You should consider using a script if you really want a name to display.
Related
I'm trying to write a cli that will take a users path that they input into the command line, then add this path to the correct path file depending on their shell - in this case zsh. I have tried using:
shell = str(subprocess.check_output("echo $SHELL", shell=True))
click.echo("Enter the path you would like to add:")
path = input()
if 'zsh' in shell:
with open(".zshrc", 'w') as zsh:
zsh.write(f'export PATH="$PATH:{path}"')
This throws no errors but doesn't seem to add to the actual ~./zshrc file.
Is there a better way to append to the file without manually opening the file and typing it in?
New to this so sorry if it's a stupid question...
Open the file in append mode. Your code also assumes that the current working directory is the user's home directory, which is not a good assumption to make.
from pathlib import Path
import os
if 'zsh' in os.environ.get("SHELL", ""):
with open(Path.home() / ".zshrc", 'a') as f:
f.write(f'export PATH={path}:$PATH')
with (Path.home() / ".zshrc').open("a") as f: would work as well.
Note that .zprofile would be the preferred location for updating an envirornent variable like PATH, rather than .zshrc.
Solved! Just want to put the answer here if anyone comes across the same problem.
Instead of trying to open the file with
with open(".zshrc", 'w') as zsh:
zsh.write(f'export PATH="$PATH:{path}"')
you can just do
subprocess.call(f"echo 'export PATH=$PATH:{path}' >> ~/.zshrc", shell=True)
If anybody has a way of removing from ~/.zshrc with python that would be very helpful...
Instead of opening all the programs and files one by one to edit my website when I turn on my computer, I want to execute a python script to open them all for me. However, when I run it, it is always opening an index.html file in a folder titled 'index'. I want it to open up say, webpages.html in the 'webpages' folder.
#!/usr/bin/env python
import os, webbrowser, subprocess
os.chdir('C:/Users/Bruin/Desktop/My_Webpage')
current_path = os.getcwd()
file_to_open = input('What filename to open?')
print("hello")
#subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\'' + file_to_open + r'\'' + file_to_open + r'.html'])
subprocess.call([r'C:\Users\Bruin\AppData\Local\atom\atom.exe', r'C:\Users\Bruin\Desktop\My_Webpage\webpages\webpage.html'])
webbrowser.open('file:///C:/Users/Bruin/Desktop/My_Webpage/index/index.html', new=2)
I commented out where I used the inputed variable because even explicitly typing in what I want to open directly into the script, it is not working. It is opening up in the browser just fine.
I am also working in PyCharm, do not know if that matters. It didn't work in IDLE either. I'm lost on where to go.
It is a code to rename all the files in a given directory but it seems while running in my terminal it giving me a syntax error at the print statement. Also if I comment the statement I get an error at the if statement of main. If I remove that too I get an error at the rename_files() function call statement.
import os
def rename_files():
#Get all the files from directory
file_list = os.listdir("/Users/arpitgarg/test")
print file_list
#Rename all the files.
for file_name in file_list:
os.rename(file_name, file_name.translate(None, "0123456789")
print file_name
if __name__ == '__main__':
rename_files()
I doubt the trace back error is 'can't find the file specified', if so your py script needs to know where the files to rename; cause its not in the current working directory.
You'll have to add:
os.chdir('the exact path to files to be renamed')
before the for loop
The file_names function does not contain a properly indented statement . Neither does the if name=='main' conditional. Also, the os.rename function call is missing a closing parenthesis . Try using a IDE next time , like pyCharm. It will highlight these syntax errors to you.
When asking for help, provide us with the necessary information to help.. in this case the actual Traceback.
As stated before, the indentation is one major error. Python uses whitespace to differentiate code blocks. http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Indentation
I recommend using PyCharm, as also stated before, but it is a memory hog. If running on an older computer, I would recommend using Notepad++ or PyScripter.
Trying to call a python script on Vba and I am a newb. I tried converting the main script to an exe using py2exe and then calling it from VBA (shell) but the main script calls other scripts therefore it becomes complicated and I messed it up (my exe is not functional). Besides, the the main script is a large file and I do not want to revise it a lot.
Bottomline, is there a way to call the main script from excel vba, without converting the script to an exe file.
So far, I tried:
RetVal = Shell("C:\python27\python.exe " & "import " & "C:\\" & "MainScriptFile")
It starts python.exe but does nothing else. Then I tried:
RetVal = Shell("C:\Windows\System32\cmd.exe " & "python " & "C:\\Python27\\hello.py")
It starts command prompt but does not even start python.
P.S. I checked all the related questions in the forum, they do not solve my prob.
Try this:
RetVal = Shell("<full path to python.exe> " & "<full path to your python script>")
Or if the python script is in the same folder as the workbook, then you can try :
RetVal = Shell("<full path to python.exe> " & ActiveWorkBook.Path & "\<python script name>")
All details within <> are to be given. <> - indicates changeable fields
I guess this should work. But then again, if your script is going to call other files which are in different folders, it can cause errors unless your script has properly handled it. Hope it helps.
I just came across this old post. Nothing listed above actually worked for me. I tested the script below, and it worked fine on my system. Sharing here, for the benefit of others who come to this spot after me.
Sub RunPython()
Dim objShell As Object
Dim PythonExe, PythonScript As String
Set objShell = VBA.CreateObject("Wscript.Shell")
PythonExe = """C:\your_path\Python\Python38\python.exe"""
PythonScript = "C:\your_path\from_vba.py"
objShell.Run PythonExe & PythonScript
End Sub
There are a couple of ways to solve this problem
Pyinx - a pretty lightweight tool that allows you to call Python from withing the excel process space
http://code.google.com/p/pyinex/
I've used this one a few years ago (back when it was being actively developed) and it worked quite well
If you don't mind paying, this looks pretty good
https://datanitro.com/product.html
I've never used it though
Though if you are already writting in Python, maybe you could drop excel entirely and do everything in pure python? It's a lot easier to maintain one code base (python) rather than 2 (python + whatever excel overlay you have).
If you really have to output your data into excel there are even some pretty good tools for that in Python. If that may work better let me know and I'll get the links.
To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA:
In my program
Sub runpython()
Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub
In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.
This code will works:
your_path= ActiveWorkbook.Path & "\your_python_file.py"
Shell "RunDll32.Exe Url.Dll,FileProtocolHandler " & your_path, vbNormalFocus
ActiveWorkbook.Path return the current directory of the workbook. The shell command open the file through the shell of Windows.
You can also try ExcelPython which allows you to manipulate Python object and call code from VBA.
Try this:
retVal = Shell("python.exe <full path to your python script>", vbNormalFocus)
replace <full path to your python script> with the full path
To those who are stuck wondering why a window flashes and goes away without doing anything, the problem may related to the RELATIVE path in your Python script. e.g. you used ".\". Even the Python script and Excel Workbook is in the same directory, the Current Directory may still be different. If you don't want to modify your code to change it to an absolute path. Just change your current Excel directory before you run the python script by:
ChDir ActiveWorkbook.Path
I'm just giving a example here. If the flash do appear, one of the first issues to check is the Current Working Directory.
ChDir "" was the solution for me. I use vba from WORD to launch a python3 script.
In my case, as I have my script in a different directory than my ms access document and, in that script I import variables from other scripts, I had to change the directory first. Then I can use correctly the shell function.
ChDir "C:\Users\directory_where_the_script_is"
Call Shell("C:\Users\...\python.exe " & "your_script_name.py", 1)
for me this not working
RetVal = Shell(" " & ActiveWorkBook.Path & "<python script name>")
for me this :
RetVal = Shell("python3" & " " & "C:\a\b\c\xyz.py")
I think above answers have a catastrophic problem:
after running the macro,cmd window would close automatically, instantly. In case output is not as expected you would have absolutely zero debug information.
Finally I found a better way in which case, cmd window remains open and shows all the information (print of python) and error log.
code as below:
Sub RunPythonScript()
cwd = ActiveWorkbook.Path 'current working directory
workbookName = ActiveWorkbook.Name
pythonScriptName = "main.py"
workbookNameWithPath = cwd & "\" & workbookName
pythonScriptNameWithPath = cwd & "\" & pythonScriptName
pythonExePath = "C:\Users\USERNAME\AppData\Local\Programs\Python\Python39\python.exe" ' change path as output of "where python"
Shell "cmd.exe /k """"" & pythonExePath & """ """ & pythonScriptNameWithPath & """""", vbNormalFocus
End Sub
I've got a problem with some VB scripting - it doesn't seem like it should be terribly difficult to solve, but even after trudging through many a page of Google I have yet to find a solution.
[The problem]
Here is my python file (test.py), simplified to just show the problem:
f = open("testing.txt", 'w')
f.write("oh hai\n")
f.close()
Of course, when run directly from the command line, this generates the file as you'd expect.
However, when run in a simple .vbs script (WARNING: My vbs skills are lacking. This is probably why I am having a problem. So far I haven't had many issues, apart from hating life from using XP to code when I'm used to using vim)
Set WshShell = WScript.CreateObject("WScript.Shell")
cmd = "C:\Python27\python test.py"
WshShell.Run cmd
no output file is generated! At all! It's infuriating, as when I input that exact command ("C:\Python27\python test.py") into the run program from the start menu, it works!
[System info]
At work, so they're on Windows XP. Everything else is pretty standard, or so I'm lead to believe.
EDIT: Changed "C:\Python27\testing.py" to just "testing.py". This was left over from when I was trying to solve it, and thought maybe it was putting the files somewhere outside of the destination folder.
First, your Python script looks suspicious, I doubt the backslashes work in a simple string. At least, in my test, it didn't work, I just replaced them with forward slashes.
Next, you can see the error message by prepending cmd with cmd /k, the run window remains on screen. You can see the .py file isn't found, because it isn't in the current directory. You have to specify an absolute path to this file, perhaps by getting the current path from the script.
[EDIT] I finally got a working code (my VBS is a bit rusty...)
Dim wshShell, fso, loc, cmd
Set fso = CreateObject("Scripting.FileSystemObject")
loc = fso.GetAbsolutePathName(".")
WScript.Echo loc
'~ cmd = "%ComSpec% /k C:\Languages\Python\python.exe " + loc + "\test.py"
cmd = "C:\Languages\Python\python.exe " + loc + "\test.py"
WScript.Echo cmd
Set wshShell = CreateObject("WScript.Shell")
wshShell.Run cmd
You can also check the arguments if a path is provided:
if WScript.Arguments.Count = 0 then
loc = fso.GetAbsolutePathName(".")
else
loc = WScript.Arguments(0)
end if
Such script is better run with cscript instead of default wscript.
Try
f = open("C:\\Python27\\testing.txt", 'w')
instead of your first line.