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

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

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()

Python get file relative to command line user

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.

Python 2.7.10 Prompt for user input

I'm working on an online tutorial for Python, & I'm trying to go a little farther for an example problem than it calls for.
The objective is to rename all the files in a folder. My addition is to prompt the user for the folder, rather than hardcoding it.
I've tried the suggestions in Python: user input and commandline arguments, but when I run the script no prompt text is displayed.
As it stands my script looks like this:
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in ListDir(f):
print("Current file is '" + f)
I imagine I'm misunderstanding the answers in the question I linked to, and was hoping someone could clarify the responses for me. Especially since that thread mixes 2.7 and 3.x.
Thanks!
f is undefined when you loop through it. Did you mean ListDir(Fol)? And also ListDir is undefined too.
But above all you are not calling the RName_Files function in your program, try addding RName_Files() at the end of the script.
What could work
import os
ListDir = os.listdir
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")
#Iterate through the files in the folder
for f in ListDir(Fol):
print("Current file is '" + f)
if __name__ == "__main__":
RName_Files()
You should also follow the PEP8 naming conventions for variables and function names. In python variables and functions are snake_case, while class names are CamelCase. And you can also be more clear with your names, rename_files instead of RName_Files, folder or path instead of Fol, file_name instead of f.
Which will look like this:
from os import listdir
def rename_files():
#Get the folder to user
path = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")
#Iterate through the files in the folder
for file_name in listdir(path):
print("Current file is " + file_name )
# do something with file_name
if __name__ == "__main__":
rename_files()
You need to call your method
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in os.listdir(fol):
print("Current file is '" + f)
RName_Files()
The "pythonic" way to do this would be like this:
import os
import sys
import optparse
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point
#Iterate through the files in the folder
for f in ListDir(Fol):
print("Current file is '" + f)
def main():
RName_Files()
if __name__ == "__main__":
main()
Basically you defined your function using def but never actually called it. Its good practice to have a main function to call the ones you've created and to call them in this fashion.

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)

Executing linux command with variable using python

I'm writing a python script which should give the string inside the .dll file and these files stored in directory. The script is
import sys
import os
def main():
for lst in os.listdir("dir name"):
print lst
os.system("strings"+" "+lst)
if __name__ == "__main__":
main()
This code is listing the files of the directory but it is not executing the command, giving error
**strings: 'filename' no such file **
What is the issue with this script ?
You have a problem with filenames that contain spaces or other special characters.
You can try:
def quote(s):
return "'" + s.replace("'", "'\\''") + "'"
def main():
for lst in os.listdir("."):
print lst
os.system("strings " + quote(lst))
PS with Python 3.3 (or greater), use shlex.quote instead

Categories