Let me first say that I'm a newbie to python, and I've written a python shell named test.py. The content is as follows:
#!/usr/bin/python
import os
cur_dir = os.getcwd();
print 'hello world' > cur_dir+"/test.log" 2>&1
When I run test.py by "python test.py", it says:
File "test.py", line 4
print 'hello world' > cur_dir+"/test.log" 2>&1
^
SyntaxError: invalid syntax
Could anyone give me some idea? Thanks!
P.S.
what I want is to write a string in test.log file. That's all. As I said first, I'm REALLY new to python, so please don't be so harsh to me :), I'm gonna read through the tutorial first to have a glimpse of python, Thanks to all you guys!
You are using invalid syntax. As a result Python gives you the error:
SyntaxError: invalid syntax
To fix this, stop using the invalid syntax.
Also in the future, explain what you are trying to achieve, and your answers are likely to tell you how to achieve that.
The invalid syntax looks like it's a bash redirection of stderr to stdout which makes no sense in the context above, so it's not possible to figure out what you are actually trying to do.
To write to a file you do this:
thefile = open('path_to_the_file', 'wt')
thefile.write('The file text.\n')
However, to do logging, you are better off using the logging module.
Use '>>' with print to redirect it to an alternate stream.
See How to print to stderr in Python?
Related
I am currently working on a python script in which there is a moment I want to delete a file which name is ending with .txt
To do so I just run a command line using os in python:
os.system("del working/*.txt")
When running the python script, I get the following error in cmd:
Option non valide - "*". which can be translated "Invalid option"
It seems that the wildcard isn't recognized by cmd but I know very little about this. Why is it not working ?
I know I could handle the situation with regular expressions but I'd like to understand.
Thank you in advance
In Windows, \ is the path delimiter, not /, so you should do:
os.system(r"del working\*.txt")
Note that / in Windows is for switches, hence the "invalid option" error.
I think its better use os.remove instead os.system with "del" command. Using os.system your script will not work on linux. Here a example using os.remove:
files = os.listdir("working\")
for fi in files:
if fi.endswith(".json"):
os.remove("working\{}".fomat(fi))
I am writing a program where you need to input a title for a file. If you want to delete the file, the command ss "rm name_of_file".
Here Is My Code:
import os
title = raw_input("What Will Your Title Be? ")
os.system("rm", title)
As you can probably imagine, that is only a very small part of the program I am writing.
The Error I Am Getting Is:
File "./texts.py", line 1446, in <module>
os.system("rm", title)
TypeError: system() takes exactly 1 argument (2 given)
I am probably just wording this wrong, and some feedback would be helpful :)
The comma separates it into two arguments, so you are getting that error because that function only takes one argument. Change it so you are adding to the same string thus submitting just one argument to make it work:
os.system("rm "+title)
This is going to be exceedingly hard to implement safely. Consider the case when someone types -rf / as the filename to delete. I'd strongly suggest using the os.unlink function instead:
>>> import os
>>> os.unlink('-rf /')
...
OSError: [Errno 2] No such file or directory: '-rf /'
This is a dangerous operation to attempt on your own. Let the standard library do the heavy lifting for you.
Why don't you just do
if os.path.isfile(title):
os.remove(title)
I would like to know if it's possible to check if a Python code has a correct syntax, without running it, and from a Python program. The source code could be in a file or better in a variable.
The application is the following: I have a simple text editor, embedded in my application, used for editing Python scripts. And I'd like to add warnings when the syntax is not correct.
My current idea would be to try importing the file and catch a SyntaxError exception that would contains the erroneous line. But I don't want it to execute at all. Any idea?
That's the job for ast.parse:
>>> import ast
>>> ast.parse('print 1') # does not execute
<_ast.Module at 0x222af10>
>>> ast.parse('garbage(')
File "<unknown>", line 1
garbage(
^
SyntaxError: unexpected EOF while parsing
I just found out that I could probably use the compile function. But I'm open to better suggestions.
import sys
# filename is the path of my source.
source = open(filename, 'r').read() + '\n'
try:
compile(source, filename, 'exec')
except SyntaxError as e:
# do stuff.
You could use PyLint and call it when the file is saved, and it'll check that file for errors (it can detect much more than just syntax errors, look at the documentation).
Sorry I am not familar with Python...
It gives me the following error message
File "gen_compile_files_list.py", line 36
print 'java files:', n_src
^
SyntaxError: invalid syntax
I.e. caret points to last quote. What's wrong with it?
OS Windows 7, Python version 3.2.2
On Python 3, print is a function. You need this:
print('java files:', n_src)
print changed syntax between Python2 and Python3; it is now a function.
You would need to change:
print 'java files:', n_src
to
print('java files:', n_src)
Alternatively, you can try converting the code from Python2 to Python3 syntax with the 2to3 tool. Here is more information on the transition if you are interested. This way you can maintain a single code base that works on both versions.
As you are not familiar with python, try installing Python 2 instead and running the code with that.
print is a function in Python 3+. So:
print ('java files:', n_src)
I have a simple python script like so:
import sys
lines = sys.argv[1]
for line in lines.splitlines():
print line
I want to call it from the command line (or a .bat file) but the first argument may (and probably will) be a string with multiple lines in it. How does one do this?
Of course, this works:
import sys
lines = """This is a string
It has multiple lines
there are three total"""
for line in lines.splitlines():
print line
But I need to be able to process an argument line-by-line.
EDIT: This is probably more of a Windows command-line problem than a Python problem.
EDIT 2: Thanks for all of the good suggestions. It doesn't look like it's possible. I can't use another shell because I'm actually trying to invoke the script from another program which seems to use the Windows command-line behind the scenes.
I know this thread is pretty old, but I came across it while trying to solve a similar problem, and others might as well, so let me show you how I solved it.
This works at least on Windows XP Pro, with Zack's code in a file called
"C:\Scratch\test.py":
C:\Scratch>test.py "This is a string"^
More?
More? "It has multiple lines"^
More?
More? "There are three total"
This is a string
It has multiple lines
There are three total
C:\Scratch>
This is a little more readable than Romulo's solution above.
Just enclose the argument in quotes:
$ python args.py "This is a string
> It has multiple lines
> there are three total"
This is a string
It has multiple lines
there are three total
The following might work:
C:\> python something.py "This is a string^
More?
More? It has multiple lines^
More?
More? There are three total"
This is the only thing which worked for me:
C:\> python a.py This" "is" "a" "string^
More?
More? It" "has" "multiple" "lines^
More?
More? There" "are" "three" "total
For me Johannes' solution invokes the python interpreter at the end of the first line, so I don't have the chance to pass additional lines.
But you said you are calling the python script from another process, not from the command line. Then why don't you use dbr' solution? This worked for me as a Ruby script:
puts `python a.py "This is a string\nIt has multiple lines\nThere are three total"`
And in what language are you writing the program which calls the python script? The issue you have is with argument passing, not with the windows shell, not with Python...
Finally, as mattkemp said, I also suggest you use the standard input to read your multi-line argument, avoiding command line magic.
Not sure about the Windows command-line, but would the following work?
> python myscript.py "This is a string\nIt has multiple lines\there are three total"
..or..
> python myscript.py "This is a string\
It has [...]\
there are [...]"
If not, I would suggest installing Cygwin and using a sane shell!
Have you tried setting you multiline text as a variable and then passing the expansion of that into your script. For example:
set Text="This is a string
It has multiple lines
there are three total"
python args.py %Text%
Alternatively, instead of reading an argument you could read from standard in.
import sys
for line in iter(sys.stdin.readline, ''):
print line
On Linux you would pipe the multiline text to the standard input of args.py.
$ <command-that-produces-text> | python args.py