Running python file through VS Code terminal - python

My question is I am unable to run a python file in VS Code terminal unless I specify the full path.
Whereas, when I see any python tutorial, only python filename is entered and it works.
Can somebody pls help me with this issue?

The files need to be in the same folder where you are operating / or have the other Python files.
You can use two ways for this:
first:
import os
pwd = os.getcwd()
# again, make sure you file is in the same directory.
the_file = (pwd + "\\filename.xlsx")
or Secondly,
#the below you can use wherever your file is and it will locate it.
# you specify the full path using pathlib.path and:
pathlib.path(directory here without the file itself).joinpath(file name here).

Related

Python/Jupyter getting a FileNotFoundError when attempting to read an excel file however said file is in the correct directory

data = pd.read_excel("ETH-USD")
I continually receive an error message informing me that the file cannot be found
this is despite the fact that
1: my directory has been changed within to Python to the same address as the folder where the excel file is stored
2: the file name is input exactly as displayed
Any ideas on why it is unable to find my file?
Is it possible that the excel file has an extension of .xlsx, but your file explorer is set to "hide file extensions"? Try:
data = pd.read_excel("ETH-USD.xlsx")
Or, see what's in the current directory by running:
import os
print(os.listdir())
A tip from the comments:
Windows tip too: hold Shift, right click the excel file and copy as path, then you can see its path (if you don't enable viewing file extensions in the file browser). –
creanion
Often when running python scripts from compilers the "working directory", or where you are running the script from doesn't match the location of your script, hence why I find it much more reliable to use this instead:
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
data = pd.read_excel(os.path.join(BASE_DIR,"ETH-USD")
To add, while I do not use Jupyter, in VSCode which I use, the working directory (which is where python looks for if you put a path in read_excel() but its not a full path) is often the current directory opened in there, so I expect a similar issue to be the reason for your issue.

Run Python Script From Script Directory/Current Directory

[Introduction]
Hi! I'm working on a python script to automate installation of UWP-Apps, it's been a long time i'm not touching Python; until this day. The script uses Depedencies inside the script directory, i've looking up on my older scripts and found this specific code.
os.chdir(os.path.dirname(sys.argv[0]))
[Problematic]
However, using the above code doesn't work on my current script but it's working fine on older scripts. When using above, it shows:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: ''
Already looking up on Internet about this topic; but most of them was talking about running the script from outer/different directory that leads me to dead end.
Any helps is appreciated :)
The easiest answer is probably to change your working directory, then call the .py file from where it is:
cd path/to/python/file && python ../.py
Of course you might find it even easier to write a script that does it all for you, like so:
Save this as runPython.sh in the directory where you're running the python script from, is:
#!/bin/sh
cd path/to/python/file
python ../script.py
Make it executable (for yourself):
chmod +x ./runPython.sh
Then you can simply enter your directory and run it:
./runPython.sh
If you want to only make changes to the python script:
mydir = os.getcwd() # would be the folder where you're running the file
mydir_tmp = "path/to/python/file" # get the path
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd()
The reason you got an error was because sys.argv[0] is the name of the file itself, instead you can pass the directory as a string and use sys.argv[1] instead.
import os
from os.path import abspath, dirname
os.chdir(dirname(abspath(__file__)))
You can use dirname(abspath(__file__))) to get the parent directory of the python script and os.chdir into it to make the script run in the directory where it is located.

CMD can't normaly read 'C:\Program Files'

I have some problem with my WIndows CMD.
Some time I need to open python file using CMD command. And I write: 'C:\Program Files\Python X.X\python.exe file.py' but have error: 'C:\Program' isn't system command (maybe not the same, I have another OS language).
With different methods I have different errors but can't open python file.
Examples:
(Picture) translate: can't find 'C:\Program'...
(Picture) another example when I trying to write python directory first and then start python file, but it can't find python file.
Thanks for helping me.
There seems to be 2 different problems here.
Windows does not recognise spaces in directory or file names on the command line, so you need to put the directory insied "" .
i.e. "C:\Program Files\Python 3.4\python.exe"
In your second picture, suggests that run.py does not exist in the current directory. Change Directory to where the run.py file is before running that command.
First of all go to the directory where your python file is located ... like:
cd "c:\users\someone\documents\..."
On your pictures you are trying to run python file located in system32 folder but i guess it is not located there so move where the file is with that cd command
Then as Martin says the problem with path of python.exe is the space between words. To solve put the path into quotation marks.
But u can add python to system path and insted of writing full path u can write only
python file.py
How to add python to path see here https://superuser.com/questions/143119/how-to-add-python-to-the-windows-path

Full File Path vs. Short OSX

I'm running OSX Mavericks but this problem has been going on since I had Snow Leopard.
When writing a script in any language, eg: Python. When I try to open a file the short
form doesn't work.
file = open('donkey.jpg')
And I get this error:
IOError: [Errno 2] No such file or directory: 'donkey.jpg'
Instead, I always have to specify the full path.
file = open('/Users/myName/Desktop/donkey.jpg')
Any ideas on why this could be happening and how to correct it?
If you specify donkey.png, it means donkey.jpg file in the current working directory. (relative path)
Make sure you're running the script in the same directory where donkey.jpg exists.
If you want specify the image file path relative to the script file instead of current working directory use following:
import os
filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'donkey.jpg')
NOTE You can use __file__ only in script file. (not in interactive mode)
Your open call does not have a mode parameter. In which case, it defaults to opening the file in read mode.
Unless the file you are opening (to read) resides in the current working directory, it is completely expected that the python script throws a IOError.

Crontab Python Script Execution (Can't find settings config file)

My Crontab -l
# m h dom mon dow command
SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
00 8,20 * * * python /home/tomi/amaer/controller.py >>/tmp/out.txt 2>&1
My controller.py has config file settings.cfg also it uses other script in the folder it's located (I chmoded only controller.py)
The error
1;31mIOError^[[0m: [Errno 2] No such file or directory: 'settings.cfg'
I have no idea how to fix this? Please help me?
Edit: The part that read the config file
def main():
config=ConfigParser.ConfigParser()
config.readfp(open("settings.cfg"),"r")
As I initially wrote in my comment, this is because you are using relative path to the current working directory. However, that is not going to be the same when running all this via the cron executable rather than the python interpreter directly via the shebang.
Your current code would look for the "settings.cfg" in the current working directory which is where the cron executable resides, and not your script. Hence, you would need to change your code logic to using absolute paths by the help of the "os" built-in standard module.
Try to following line:
import os
...
def main():
config = ConfigParser.ConfigParser()
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
settingsFilePath = os.path.join(scriptDirectory, "settings.cfg")
config.readfp(open(settingsFilePath,"r"))
This will get your the path of your script and then appends the "settings.cfg" with the appropriate dir separator for your operating system which is Linux in this particular case.
If the location of the config file changes any time in the future, you could use the argparse module for processing a command line argument to handle the config location properly, or even without it simply just using the first argument after the script name like sys.argv[1].
Your code is looking for settings.cfg in its current working directory.
This working directory will not be the same when cron executes the job, hence the error
You have two "easy" solutions:
Use an absolute path to the config file in your script (/home/tomi/amaer/config.cfg)
CD to the appropriate directory first in your crontab (cd /home/tomi/amaer/ && python /home/tomi/amaer/controller.py)
The "right" solution, though, would be to pass your script a parameter (or environment variable) that tells it where to look for the config file.
It's not exactly good practice to assume your config file will always be lying just next to your script.
You might want to have alook at this question: https://unix.stackexchange.com/questions/38951/what-is-the-working-directory-when-cron-executes-a-job

Categories