Autocomplete filename in python script [duplicate] - python

This question already has answers here:
Tab completion in Python's raw_input()
(4 answers)
Closed 4 years ago.
I have made a python script that asks the user to enter 2 or 3 filenames, which should be analysed. The filename insertion is done in the script (it is not passed as argument to argparse, because there are other choices that user has to make before that). Due to the company naming convention these filenames can be quite long and thus cumbersome to type. To help the user I am printing the contents of directory. For now I am using something like this:
fname = raw_input("Insert phase 1 filename: ")
(than I check the if file exists etc...)
Is there a way to implement autocomplete for filenames inside the python script by writing custom input() function?
Note that the script must run on different machines / OS and I can not ask users to install some non-standard python libraries.
If there is no clean way to do it I might use less fancy solution of just printing a number before the filenames in the directory and than ask the user to insert just the number.

This might help:
Tab completion in Python's raw_input()
If you don't want to use that and just "guess" the file:
commands = ["cute_file", "awesome_file"]
def find_file(text):
options = [i for i in commands if i.startswith(text)]
if len(options):
return options
else:
return None
my_input = input("File name:")
print(find_file(my_input))

Related

How do I assign myString to an imported Python function in a bash shell?

I have a little homework webpage. I'm trying to automate the production of the webpage each week.
I know very little about this. Wednesday I asked about importing Python functions that I made. I think I have grasped the concept. I've tested everything in Idle. All the modules work.
In my Python shell, (I use Idle in Ubuntu), everything does what I want.
I first append the paths:
for i in range(0, len(pyPaths)):
sys.path.append(pyPaths[i])
then import the modules:
from makeRBsInlineV1 import makeHTMLrbsNums
from makeCheckboxesInlineV1 import makeHTMLCBs
from makeDropdownboxesInlineV1 import makeDropdownboxes
from createhtmlTableInlineV1 import makeHTMLtable
from makeRBsInlineV2 import makeHTML_RBs
from readLinesTextboxesInlineV1 import readLinesmakeTBs
from makeThankyouPHPInlineV1 import makeThankyouPHP
All these modules return a text string which is a mixture of html tags + my text. It displays nicely in Firefox.
In Idle I just write, for example:
myString = readLinesTextboxesInlineV3()
it asks me a few questions and off it goes. Afterwards, myString is ready to be put in the webpage text string.
However, in bash, I cannot write
myString = readLinesTextboxesInlineV3()
in bash, I cannot write
myString = input('Enter the name of the module you want. ')
and then enter,
readLinesTextboxesInlineV3()
because then myString is just the input text, not the function.
Each week things are different, I may need to run 2 or more of the modules, add the result strings, then write them in the webpage text string at the correct place.
I run this in a
while True:
loop, so I can add strings from various modules.
For any given week, I don't know which module I want to use, so I make them all available.
I have a list of all the modules:
pyFiles = ['makeCheckboxesInlineV1()', 'dropdownboxesInlineV1()',
'createhtmlTableInlineV1()', 'makeRBsInlineV2()',
'readLinesTextboxesInlineV3()', 'makeThankyouPHPInlineV1()']
How do I assign myString to any 1 of the modules above when I run makeWebpage.py in bash?
I tried this:
pyFiles = [makeHTMLCBs(), makeDropdownboxes(), makeHTMLtable(), makeHTML_RBs(), readLinesmakeTBs(), makeThankyouPHP()]
Declare a list of the functions. Trouble is, as soon as I do that, Python wants to run the first function immediately. I was hoping I could enter a number and run say:
myString = pyFiles[3]
The best solution for you is to add arguments to your python script that can be added as flag to your command line.
This way you could call your script like the following from the shell (example):
python makeWebpage.py --module "makeCheckboxesInlineV1"
Python standard library provide argparse module for that specific need. It's really easy to handle and transform shell argument into python variable.
I recommend that you read that blog post which I found myself really useful. The part you need the most is What about argparse?
Add something like this in your main:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument('-m', '--module', action='store_true')
args = parser.parse_args()
module = args.module # The variable module now is a String containing "makeCheckboxesInlineV1"

Unix like use of variables in python [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I am fairly new to Python and trying to figure out way to use variables from file as described below.
I have a file query.txt
query1="select count(*) from table1;"
query2="select count(*) from table2;"
My main program:
conn=connect_db()
print >>log,"connection successful"
c=conn.cursor()
with open('query.txt') as fp:
for line in fp:
print line
i=1
query="query"+str(i) #If I print query I get query1
#I am looking to pass query1 as argument, to execute first query
c.execute(query);
r=c.fetchone()
print r
i+=1
In shell I would use c.execute($query) and it would replace it with it's assigned value. How do I achieve it with Python?
Appreciate your help and guidance.
Change query.txt to:
select count(*) from table1;
select count(*) from table2;
Then in Python:
for query in fp:
c.execute(query)
You can use the sys library for that. https://docs.python.org/2/library/sys.html?highlight=argv#sys.argv
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.
Argv allows you to pass parameters from the commandline when running your script. A tutorial can be found here:
https://www.tutorialspoint.com/python/python_command_line_arguments.htm
[EDIT]
2 Assumptions:
You are working with python 2.7
Your script runs commandline in
Linux.
Not saying it won't work otherwise, but this is what I know works.
[EDIT2]
Alex Hall's answer is actually what the OP needed, so focus on that one instead.

How to store user input in txt file?(Python 3) [duplicate]

This question already has answers here:
.write not working in Python
(5 answers)
Closed 6 years ago.
So i am writing a program and i made a function which stores user data in a txt file.It is like a simple registration function.The user gives the username and password to store.Problem is i can't store user input in the file.
My code is :
def reguser(): #Function name.
fwu = open('user.txt','w') #create or open user.txt file.
user = input("Username: ") #takes the user input.e.g what username to register
fwu.write(user) #this command should write input into the file
fwp = open('pass.txt','w') #create or open pass.txt file.
pas = input ("Password: ") #takes user input e.g what password to register
fwp.write(pas) #write the password into the file
print ("To check for registraion completion, please login.")
askuser()
So what i get is two text files user and pass but they are empty.
What am i doing wrong??
and please do not tell me to use modules for registraion.
Regards ali7112001
You didn't fwu.close() or fwp.close() (you didn't save it). Also a quick look up next time would save you some time. .write not working in Python
Please try with raw_input() instead of input()
Also please close() the files.

How to search and return across multiple files? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Hi I was looking for some help and a starting point that would help me find a word or a phrase across multiple files so instead of CTRL + F and typing out the word to search in each individual file I could open all these files in python, run a search command, and it would give me the file names that return the key word. Any help appreciated.
import os
import os.path
for fname in os.listdir('.'):
if os.path.isfile(fname):
f = open(fname)
if 'mystring' in f.read():
print fname
f.close()
You will need more than this if you need to search through subdirectories, but this will search every file in the current directory for an instance of mystring.
You can definitely make your own functionality as per your requirement in python if you want. I have not worked on python so far. I can give you general idea or logic to implement this functionality.
Take two arguments from users. First argument can be string or pattern of string for which you want search in multiple files. Second argument can be path to that folder in which you want to perform search.
Once you get path to that folder you can iterate through all files and folder to that path and can perform searching of that string in individual file.
simply save the instance of that file and location of file where you find your match in any data structure.
Once you are done with all files and folder just print out all results on console.
FYI: if you want such functionality for your own convenience then any operating system provides inbuilt functionality. Windows has findstr and linux has grep function.
Simplest would be something like...:
import fileinput
word = raw_input('Word to search for: ')
for line in fileinput.input():
if word in line:
print(fileinput.filename())
fileinput.nextfile()
This is meant to be called with the files of interest on the command line -- so it's quite Unix-focused (as in Unix the shell will expand wildcards for you and the program receives the file names as arguments); in Windows you might have to do your own globbing.
In Python 3, change raw_input to input, but otherwise the code is the same.
It would be more elegant to pass the word to search for as the first argument, have some good default for what to do when called without file arguments, etc, etc, but all of these small complications will have to wait until you have clarified your exact requirements a lot better (what platform, what Python release, and so forth).

how can I input a file and run an asynchronously command on it in python?

I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error:
NameError: name 'example.bam' is not defined
I tried many things but I couldn't fix it. Can someone tell me what is wrong?
This is my comand:
from subprocess import call
filename = input ("filename: ");
with open (filename, "r") as a:
for command in ("samtools tview 'a' /chicken/chick_build2.1_unmasked.fa",):
call(command, shell=True)
This is a short version of my command: it has to do much more stuff. I'm also thinking to input 4-6 files at same time (perhaps this information is helpful to clarify my intentions).
input is equivalent to eval(raw_input(prompt)). So what your script currently tries to do is interpret your input ("example", in your case), and execute as if it were a statement in your script. For user input (and might I simply say "for any input" -- unless you know what you're doing), always use the raw_input function.
So, to solve it, replace input with raw_input:
filename = raw_input("filename: ")

Categories

Resources