Python get file relative to command line user - python

I'm writing a python script that will be aliased and run from various directories like this:
# working
python myScript.py file.txt
or:
# not working
python script/myScript.py other_file.txt
I'm referencing the file input like this:
file = sys.argv[1]
How can I have the script look for the file based on the command line users location instead of relative to the script's location?

Try this:
import os
print(os.getcwd())
This will give you the current working directory(cwd). And using other functions like os.path.join, you can achieve what you want.
Full example:
import os
import sys
def main():
if len(sys.argv) < 2:
print('Not enough arguments.')
sys.exit(1)
print('Current working directory: %s' % os.getcwd())
print('What you want: %s' % os.path.join(os.getcwd(), sys.argv[1]))
if __name__ == '__main__':
main()
Try using it.

Related

How can I get a PyInstaller executable to create a file in the same directory?

I found the answer
So it looks like PyInstaller actually runs in a temp directory, not your own, which explains my issue. This is an explanation for that. I guess I will keep this up incase people in the future have problems.
Original question
I am trying to use PyInstaller to create an executable of a simple python script called test.py that just creates a text file and adds numbers to it, as a test of PyInstaller. This file works correctly when run normally.
from os.path import dirname, abspath
def main():
txtfile = dirname(abspath(__file__)) + '/text.txt'
with open(txtfile, 'w') as f:
for num in range(101):
f.write(str(num) + '\n')
if __name__ == '__main__':
main()
print('script executed')
When I use:
pyinstaller test.py --onefile in the same directory as test.py it successfully creates the dist file with the binary file test inside of it.
when I cd dist and do ./test to execute the file inside dist it successfully prints out main called and script executed but it doesn't actually create the file. So, main is being called and the script is being executed, but the file isn't created at all, and I am quite confused about what I'm doing wrong..I must be getting file paths messed up? But I have specified the exact full path with os.path, so it doesn't make sense to me.
The system exit code is 0, and there are no errors raised when I call ./test
I found this that shows that PyInstaller will save to a temp file. I created this script below to check if the script is being executed directly or via PyInstaller.
import os
import sys
def create_file(path):
with open(path + '/test.txt', 'w') as f:
for num in range(101):
f.write(str(num) + '\n')
def check_using_pyinstaller():
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
return application_path
return os.path.dirname(os.path.abspath(__file__))
def main():
path = check_using_pyinstaller()
os.chdir(path)
create_file(path)
if __name__ == '__main__':
main()

How do I run python script on specific folder

I'm trying to run my python script against specific folder when I specify the folder name in the terminal e.g
python script.py -'folder'
python script.py 'folder2'
'folder' being the I folder I would like to run the script in. Is there a command line switch that I must use?
The cd command in the shell switches your current directory.
Perhaps see also What exactly is current working directory?
If you would like your Python script to accept a directory argument, you'll have to implement the command-line processing yourself. In its simplest form, it might look something like
import sys
if len(sys.argv) == 1:
mydir = '.'
else:
mydir = sys.argv[1]
do_things_with(mydir)
Usually, you would probably wrap this in if __name__ == '__main__': etc and maybe accept more than one directory and loop over the arguments?
import sys
from os import scandir
def how_many_files(dirs):
"""
Show the number of files in each directory in dirs
"""
for adir in dirs:
try:
files = list(scandir(adir))
except (PermissionError, FileNotFoundError) as exc:
print('%s: %s' % (adir, exc), file=sys.stderr)
continue
print('%s: %i directory entries' % (adir, len(files)))
if __name__ == '__main__':
how_many_files(sys.argv[1:] or ['.'])

Python script won't print when called from another python script

I have two scripts. The first script outputs to a file a list of folders and files, then it calls a second python script to read that file and print it to screen. The second script is called but nothing ever prints to the screen and I'm not sure why. No error message is thrown.
First Script:
#!/bin/python
from subprocess import call
import os.path
import os
def main():
userRequest=raw_input("""Type the path and folder name that you'd like to list all files for.
The format should begin with a slash '/' and not have an ending slash '/'
Example (/var/log) *Remember capital vs. lower case does matter* :""")
userInputCheck(userRequest)
def userInputCheck(userRequest):
lastCharacter=userRequest[-1:]
if lastCharacter=="/":
userRequest=userRequest[:-1]
folderCheck=os.path.isdir(userRequest)
if folderCheck != True:
print("\nSorry, '"+userRequest+"' does not exist, please try again.\n")
requestUserInput()
else:
extractFileList(userRequest)
def extractFileList(userRequest):
fileList=open('/tmp/fileList.txt', 'a')
for folderName, subFolderName, listFiles in os.walk(userRequest):
fileList.write(folderName+":\n")
for fileName in listFiles:
fileList.write(fileName+"\n")
fileList.write("\n")
fileList.close
os.system("readFile.py /tmp/fileList.txt")
if os.path.isfile("/tmp/fileList.txt"):
os.remove("/tmp/fileList.txt")
if __name__ == "__main__":
main()
Second Script:
#!/bin/python
import sys
userFile=sys.argv[1]
f = open(userFile, 'r')
fileInfo=f.read()
sys.stdout.write(fileInfo)
sys.stdout.flush()
f.close

Trying to access a file located on a flashdrive

I have made a simple test code in python that reads from a text file, and then preforms an action if the text file contains a line "on".
My code works fine if i run the script on my hardive with the text file in the same folder. Example, (C:\Python27\my_file.txt, and C:\Python27\my_scipt.py).
However, if I try this code while my text file is located on my flashdrive and my script is still on my hardrive it won't work even though I have the correct path specified. Example, (G:\flashdrive_folder\flashdrive_file.txt, and C:\Python27\my_scipt.py).
Here is the code I have written out.
def locatedrive():
file = open("G:\flashdrive_folder\flashdrive_file.txt", "r")
flashdrive_file = file.read()
file.close()
if flashdrive_file == "on":
print "working"
else:
print"fail"
while True:
print "trying"
try:
locatedrive()
break
except:
pass
break
The backslash character does double duty. Windows uses it as a path separator, and Python uses it to introduce escape sequences.
You need to escape the backslash (using a backslash!), or use one of the other techniques below:
file = open("G:\\flashdrive_folder\\flashdrive_file.txt", "r")
or
file = open(r"G:\flashdrive_folder\flashdrive_file.txt", "r")
or
file = open("G:/flashdrive_folder/flashdrive_file.txt", "r")
cd /media/usb0
import os
path = "/media/usb0"
#!/usr/bin/python
import os
path = "/usr/tmp"
# Check current working directory.
retval = os.getcwd()
print "Current working directory %s" % retval
# Now change the directory
os.chdir( path )
# Check current working directory.
retval = os.getcwd()
print "Directory changed successfully %s" % retval
Use:
import os
os.chdir(path_to_flashdrive)

How do I get the location of the entry module in python?

I know I can use __file__ and os.path.* to figure out the path of the current module. What about the entry module?
I'm trying to load an ini file into ConfigParser from a module based on the hostname, but I want it to be relative to the entry assembly, not necessarily the working directory. Is this possible?
If by entry module you mean the program's entrypoint this is usually sys.argv[0]. So you could do something like this:
Example:
import os
import sys
def main():
basedir = os.path.dirname(sys.argv[0])
print "base directory: {0:s}".format(basedir)
if __name__ == "__main__":
main()

Categories