let say the path is Desktop\Chem\test.png
i want to print the name of the file without the .png
this is my code
def test():
file=pickAFile()
shortFile=getShortPath(file)
end = shortFile.split('\\')[1]
print"this is a",end
so the solution would be "this is a test" instead of "this is a test.png"
First off, you should probably be using os.sep instead of an explicit \ (so this will work on windows, linux, OS-X, etc. instead of just windows, but better yet, in this case, use os.path.splitext and os.path.basename (as documented in the jython docs which appear to exactly match the python equivalent
something like:
import os
def test():
file=pickAFile()
shortFile=getShortPath(file) #assume this returns c:\foo\bar\test.png
basename = os.path.basename(shortFile) # returns test.png
end,ext = os.path.splitext(basename) # this returns test,png
print"this is a",end,"which is a",ext,"file"
Related
I am using a tool named https://github.com/epinna/tplmap which tests for Template Injection in a site. This is how it test for each url
python tplmap.py -u https://leadform.microsoft.com/?lang=FUZZ
Developer has not included option for multiple urls
How can i use awk/sed/cat to add multiple urls from a text file?
Developer has not included option for multiple urls
I have look at tplmap.py and it seems viable to alterting so it would work as you wish, thing which needs change is function named main which looks as follows
def main():
args = vars(cliparser.options)
if not args.get('url'):
cliparser.parser.error('URL is required. Run with -h for help.')
# Add version
args['version'] = version
checks.check_template_injection(Channel(args))
what is happening here: args dict is created based on command line arguments, presence of url checked, version added and checking function called. I would alter that function to
def main():
args = vars(cliparser.options)
if not args.get('url'):
cliparser.parser.error('URL is required. Run with -h for help.')
# Add version
args['version'] = version
url_filename = args['url']
with open(url_filename, 'r') as f:
for line in f:
args['url'] = line.rstrip()
checks.check_template_injection(Channel(args))
so now it does open file provided where url was earlier provided for each line it is rstrip-ped to jettison trailing newline and provided as url in args then check is run. Note: I did not test that code, please apply described change and first to try use it with file holding few addresses and check if it does what you want.
For example, if I have a pipe function:
def process_data(weighting, period, threshold):
# do stuff
Can I get autocompletion on the process data arguments?
There are a lot of arguments to remember and I would like to make sure they get passed in correctly. In ipython, the function can autocomplete to show me the keyword args which is really neat, but I would like it to do this when piping a pandas dataframe too!
I don't see how this would be possible, but then again, I'm truly in awe of ipython and all its greatness. So, is this possible? If not, are there other hacks that people have come up with?
Install the pyreadline library.
$ pip install pyreadline
Update:
It seems like this problem is specific to some versions of ipython. The solution is the following:
Run below command from the terminal:
$ ipython profile create
It will create a default profile at ~/.ipython/profile_default/ipython_config.py
Now edit this ipython_config.py and add the below lines and it will solve the issue.
c = get_config()
c.Completer.use_jedi = False
Reference:
https://github.com/jupyter/notebook/issues/2435
https://ipython.readthedocs.io/en/stable/config/intro.html
[EDIT: the problem only applies with python anaconda, not with standard /usr/bin/python2.7]
[FYI: the gist referred to in this post can still be useful for anyone trying to use fortran with ctypes or cython, credit to http://www.fortran90.org/src/best-practices.html]
When using a fortran code from within python (using iso_c_bindings), either via ctypes or via cython, I ran into a weird incompatibility problem with matplotlib. Basically, if matplotlib is "activated" (via %pylab or by using pyplot.plot command), reading the namelist will omit any digit !! i.e. The value 9.81 is read as 9.00. Without matplotlib, no problem.
I made a minimal working example gist.github.com.
Basically, the fortran module just allow reading a double precision parameter g from a namelist, and store it as global module variable. It can also print its value to string, and allow directly setting its value from the outside. This makes three functions:
read_par
print_par
set_par
You can download the gist example and then run:
make ctypes
python test_ctypes.py
test_ctypes.py contains:
from ctypes import CDLL, c_double
import matplotlib.pyplot as plt
f = CDLL('./lib.so')
print "Read param and print to screen"
f.read_par()
f.print_par()
# calling matplotlib's plot command seem to prevent
# subsequent namelist reading
print "Call matplotlib.pyplot's plot"
plt.plot([1,2],[3,4])
print "Print param just to be sure: everything is fine"
f.print_par()
print "But any new read will lose decimals on the way!"
f.read_par()
f.print_par()
print "Directly set parameter works fine"
f.set_par(c_double(9.81))
f.print_par()
print "But reading from namelist really does not work anymore"
f.read_par()
f.print_par()
With the output:
Read param and print to screen
g 9.8100000000000005
Call matplotlib.pyplot's plot
Print param just to be sure: everything is fine
g 9.8100000000000005
But any new read will lose decimals on the way!
g 9.0000000000000000
Directly set parameter works fine
g 9.8100000000000005
But reading from namelist really does not work anymore
g 9.0000000000000000
The same happen with the cython example (make clean; make cython; python test_cython.py).
Does anyone know what is going on, or whether there is any workaround?? The main reason why I wrote a wrapper to my fortran code is to be able to play around with a model, set parameters (via namelist), run it, plot the result, set other parameters and so on. So for my use case this bug kinds of defies the purpose of interactivity...
Many thanks for any hint.
PS: I am happy to file a bug somewhere, but would not know where (gfortran? matplotlib?)
I workin' with Torch7 and Lua programming languages. I need a command that redirects the output of my console to a file, instead of printing it into my shell.
For example, in Linux, when you type:
$ ls > dir.txt
The system will print the output of the command "ls" to the file dir.txt, instead of printing it to the default output console.
I need a similar command for Lua. Does anyone know it?
[EDIT] An user suggests to me that this operation is called piping. So, the question should be: "How to make piping in Lua?"
[EDIT2] I would use this # command to do:
$ torch 'my_program' # printed_output.txt
Have a look here -> http://www.lua.org/pil/21.1.html
io.write seems to be what you are looking for.
Lua has no default function to create a file from the console output.
If your applications logs its output -which you're probably trying to do-, it will only be possible to do this by modifying the Lua C++ source code.
If your internal system has access to the output of the console, you could do something similar to this (and set it on a timer, so it runs every 25ms or so):
dumpoutput = function()
local file = io.write([path to file dump here], "w+")
for i, line in ipairs ([console output function]) do
file:write("\n"..line);
end
end
Note that the console output function has to store the output of the console in a table.
To clear the console at the end, just do os.execute( "cls" ).
I'm using an awk script to do some reasonably heavy parsing that could be useful to repeat in the future but I'm not sure if my unix-unfriendly co-workers will be willing to install awk/gawk in order to do the parsing. Is there a way to create a self-contained executable from my script?
I'm not aware of a way to make a self-contained binary using AWK. However, if you like AWK, chances seem good that you might like Python, and there are several ways to make a self-contained Python program. For example, Py2Exe.
Here's a quick example of Python:
# comments are introduced by '#', same as AWK
import re # make regular expressions available
import sys # system stuff like args or stdin
# read from specified file, else read standard input
if len(sys.argv) == 2:
f = open(sys.argv[1])
else:
f = sys.stdin
# Compile some regular expressions to use later.
# You don't have to pre-compile, but it's more efficient.
pat0 = re.compile("regexp_pattern_goes_here")
pat1 = re.compile("some_other_regexp_here")
# for loop to read input lines.
# This assumes you want normal line separation.
# If you want lines split on some other character, you would
# have to split the input yourself (which isn't hard).
# I can't remember ever changing the line separator in my AWK code...
for line in f:
FS = None # default: split on whitespace
# change FS to some other string to change field sep
words = line.split(FS)
if pat0.search(line):
# handle the pat0 match case
elif pat1.search(line):
# handle the pat1 match case
elif words[0].lower() == "the":
# handle the case where the first word is "the"
else:
for word in words:
# do something with words
Not the same as AWK, but easy to learn, and actually more powerful than AWK (the language has more features and there are many "modules" to import and use). Python doesn't have anything implicit like the
/pattern_goes_here/ {
# code goes here
}
feature in AWK, but you can simply have an if/elif/elif/else chain with patterns to match.
Theres a standalone awk.exe in the Cygwin Toolkit as far as I know.
You could just bundle that in with whatever files you're distributing to your colleagues.
Does it have to be self contained? You could write a small executable that will invoke awk with the right arguments and pipe the results to a file the users chooses, or to stdout - whichever is appropriate for your co-workers.
MAWK in GnuWin32 — http://gnuwin32.sourceforge.net/packages/mawk.htm
also interesting alternative, Java implementation — http://sourceforge.net/projects/jawk/