Okay, I'm a noob when it comes to Python, I have to learn this for work.. And so far, I'm looking at some small programs to list directories.
I'm using Python 3.2.1.. In the Python Shell, I make a new window and I put:
import glob
print glob.glob("/*.txt")
But when I "run module", I save it, and it always tells me Invalid syntax, and it highlights the 2nd glob in the code.. Why?? Any idea on how to fix this? I don't really understand why I have an error..
print is a function in Python 3. You can't use it as a statement like you would in the 2.x versions. Your code should work if written as:
import glob
print(glob.glob("/*.txt")) #Note the parens for print()
Related
I hope that I can ask this in a clear way, im very much a beginner to python and forums in general so I apologise if i've got anything wrong from the start!
My issue is that I am currently trying to use os.system() to enable a program to run on every file within a directory (this is a directory of ASCII tables which I am crossing with a series of other tables to find matches.
import os
for filename in os.listdir('.'):
os.system('stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits'%(filename,filename))
So what im hoping this would do is for every 'filename' it would operate this program known as stilts. Im guessing this gets interrupted/doesn't work because of the presence of apostrophes ' in the line of code itself, which must disrupt the syntax? (please correct me if I am wrong)
I then replaced the ' in os.system() with "" instead. This, however, stops me using the %s notation to refer to filenames throughout the code (at least I am pretty sure anyway).
import os
for filename in os.listdir('.'):
os.system("stilts tmatch2 ifmt1=ascii ifmt2=ascii in1=intern in2= %s matcher=2d values1='col1 col2' values2='col1 col2' params=5 out= %s-table.fits"%(filename,filename))
This now runs but obviously doesn't work, as it inteferes with the %s input.
Any ideas how I can go about fixing this? are there any alternative ways to refer to all of the other files given by 'filename' without using %s?
Thanks in advance and again, sorry for my inexperience with both coding and using this forum!
I am not familiar with os.system() but maybe if you try do some changes about the string you are sending to that method before it could behave differently.
You must know that in python you can "sum" strings so you can save your commands in a variable and add the filenames as in:
os.system(commands+filename+othercommands+filename)
other problem that could be working is that when using:
for file in os.listdir()
you may be recievin file types instead of the strings of their names. Try using a method such as filename.name to check if this is a different type of thing.
Sorry I cant test my answers for you but the computer I am using is too slow for me to try downloading python.
I need you help with nmap script and printing the output to csv file.
When I run the script and finish it with print(nm.csv()) I got the following results displayed which is what I want first place:
host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe
82.214.228.176;176.228.214.82.in-addr.arpa;PTR;tcp;21;ftp;open;;;syn-ack;;3;
82.214.228.176;176.228.214.82.in-addr.arpa;PTR;tcp;22;ssh;open;;;syn-ack;;3;
82.214.228.176;176.228.214.82.in-addr.arpa;PTR;tcp;53;domain;open;;;syn-ack;;3;
82.214.228.176;176.228.214.82.in-addr.arpa;PTR;tcp;80;http;open;;;syn-ack;;3;
But my question is how to get this redirected or to create a csv file on the same Directory from where I run the script or maybe in a path.
Thanks in advance!
You could declare a function like this one
def save_csv_data(nm_csv, path='.'):
with open(path + '/output.csv', 'w') as output:
output.write(nm_csv)
then by passing an argument you could specify another path to save the file, or otherwise, use the same directory as the script:
if (len(sys.argv) > 1 and sys.argv[1]):
save_csv_data(nm.csv(), path=sys.argv[1])
else:
save_csv_data(nm.csv())
Edit: also remember to import sys
I also would suggest you, if you decide to use arguments, use a module like argparse.
print (nm.csv(),file=open('a.csv','w'))
Edited:
You can use the print_function to get the print() behaviour from python3 in python2:
from __future__ import print_function
I am trying to write a Python script which will use openssl command to output contents of few digital certificates. The problem is that I am not able to loop through the files with the subprocess.check_output([]) function. Here's what I have got so far:-
#!/usr/bin/env python3
import subprocess
import os
import glob
for f in glob.glob("*.cer"):
OUT_PUT = subprocess.check_output(['openssl','x509','-in','f','-noout','-text'])
print(type(OUT_PUT))
print(OUT_PUT.decode('utf-8'))
I get a feeling that something's wrong with the way I am placing the "f" variable in the function. The above code does not work.
Please advise.
This may or may not be your problem, but as it stands, you have f in quotes, so you're just passing through a string ("f") rather than the name of the file you wish to pass to openssl.
I know all about how Windows uses backslashes for filenames, etc., and Unix uses forward. However, I never use backslashes with strings I create in my code. However:
When windows explorer "drops" a file onto a python script, the string it passes contains backslashes. These translate into escape sequences in the strings in the sys.argv list and then I have no way to change them after that (open to suggestions there)
Is there any way I can somehow make windows pass a literal string or ... any other way I can solve this problem?
I'd love my script to be droppable, but the only thing preventing me is windows backslashes.
EDIT:
Sorry everyone, the error was actually not the passing of the string - as someone has pointed out below, but this could still help someone else:
Make sure you use absolute path names because when the Windows shell will NOT run the script in the current directory as you would from a command line. This causes permission denied errors when attempting to write to single-part path-names that aren't absolute.
Cannot reproduce. This:
import os, sys
print sys.argv
print map(os.path.exists, sys.argv)
raw_input()
gives me this:
['D:\\workspaces\\generic\\SO_Python\\9266551.py', 'D:\\workspaces\\generic\\SO_Python\\9254991.py']
[True, True]
after dropping the second file onto the first one. Python 2.7.2 (on Windows). Can you try this code out?
I'm having trouble in my python script, and I don't understand it :
subprocess.call(['convert', file, '-crop', '80x10+90+980', '+repage', 'test.jpg'])
Returns "invalid argument - -crop"
But if I run this from the command line, it works fine :
convert test.jpg -crop 80x10+90+980 +repage test.jpg
What am I missing here ?
Is there more than one convert in the system? Try an absolute path to the command you want?
What about using the python image library instead? That seems much more reliable than to call a subprocess (especially for error handling...).
file is a _____builtin_____ class. Overriding it may produce unwanted results. Try using a different variable name.
I've actually tried your code:
>>> import subprocess
>>> subprocess.call(['convert', 'capa.jpg', '-crop', '80x10+90+980', '+repage', 'capa2.jpg'])
0
>>>
And it works for me!
So you must have something wrong, somewhere else. Check our assumptions again.