Python Invalid syntax - Invalid syntax [duplicate] - python-3.x

This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 5 years ago.
I have the following piece of code to pull the names of all files within a particular folder (including all files in it's subfolders):
import sys,os
root = "C:\Users\myName\Box Sync\Projects\Project_Name"
path = os.path.join(root, "Project_Name")
for path, subdirs, files in os.walk(root):
for name in files:
print os.path.join(path, name)
Unfortunately, it throws the following error:
> File "<ipython-input-7-2fff411deea4>", line 8
> print os.path.join(path, name)
> ^ SyntaxError: invalid syntax
I'm trying to execute the script in Jupyter Notebook. I also tried saving it as a .py file and running it through Anaconda prompt but received the same error. Can someone please point out where I'm going wrong? I'm pretty new to Python.
Thanks

in python3, print function needs to be like this :
print(os.path.join(path, name))
For more information on the changes within print function from python 2 to 3, check these links :
print is a function
pep-3105
What is the advantage of the new print function in Python 3.x over the Python 2 print statement?

This is a Python 2 Vs Python 3 issue.
In Python 2, print is used without parenthesis like:
print 42
In Python 3, print is a function and has to be called with parenthesis like:
print(42)

Related

Sys.argv list index out of range [duplicate]

This question already has answers here:
Pycharm and sys.argv arguments
(12 answers)
Closed 1 year ago.
guys. Can someone explain to me why can't I run this script (for converting a jpg into png) in PyCharm? I get an error list index out of range. I have the code and the jpg files in the same directory.
The same error occured when I ran a script to merge some pdf files (the files and the .py script were as well in the same directory).
import sys
import os
from PIL import Image
path = sys.argv[1]
directory = sys.argv[2]
if not os.path.exists(directory):
os.makedirs(directory)
for filename in os.listdir(path):
clean_name = os.path.splitext(filename)[0]
img = Image.open(f'{path}{filename}')
img.save(f'{directory}/{clean_name}.png', 'png')
print('all done!')
I think I have figured it out:
I had to add my args in my Pycharm .py script using the parameters from "modify run configuration" as in this image:
I suppose the same solution works for my image converter script.

How to use Unix regex character with python3 subprocesses run? [duplicate]

This question already has answers here:
subprocess wildcard usage
(3 answers)
Closed 3 years ago.
I'm trying to get the output from a shell command in a Python3 program. I've been looking at the documentation and this is what I've been working with:
sortered=subprocess.run(
# ['sort', time.strftime("%Y")+'*', '|', 'uniq', '-u'], # causes error did not understand * char
#['ls', '-l'], # worked fine
['sort', '2019*'], # gives same error as before
capture_output=True
)
After running the script I get back this error:
$ myscript.py
CompletedProcess(args=['sort', '2019*'], returncode=2, stdout=b'', stderr=b"sort: cannot read: '2019*': No such file or directory\n")
To_Downloadtest1.sh has been created successfully
If I run the command normally using * it works fine.
$ sort 2019*
a file.
a file.
this one is a.
this one is b.
The script is ran from the same directory that the files starting with 2019 are in.
.
├── 2019-A.txt
├── 2019-B.txt
└── myscript.py
What should happen when I run the python script is the output from the command should be put into a variable as a string. This is not happening. The only time I get an error from subprocess.run comes from using * in the command. Otherwise, I get the stdout from subprocess.run correctly. I tried ls -l as a test and it worked correctly. How can I use * with subprocess.run?
The problem here is that you don't have a shell, and so the wildcard does not get expanded.
You can use
sortered = subprocess.run('sort 2019*', shell=True, capture_output=True)
or
import glob
sortered = subprocess.run(['sort'] + glob.glob('2019*'), capture_output=True)
or, of course,
import glob
lines = []
for file in glob.glob('2019*') as handle:
lines.extend(handle.read())
sortered = sorted(lines)

How to set/define/use sys.argv

I'm fairly new to Python, so please bear with me.
Currently, I'm using Python 3.5 in an Anaconda environment on Pycharm, and I am trying to understand how to set/define/use sys.argv so that I can automate several processes before uploading my changes onto github.
For example:
python function/function.py input_folder/input.txt output_folder/output.txt
This means that function.py will take input.txt from input_folder, apply whatever script written in function.py, and store the results into output.txt in folder output_folder.
However, when I type this into terminal, I get the following error:
python: can't open file 'function/function.py': [Errno 2] No such file or directory
Then, typing sys.argv into Python console, I receive the following:
['C:\\Program Files (x86)\\JetBrains\\PyCharm 2016.2\\helpers\\pydev\\pydevconsole.py',
'53465',
'53466']
My guess is that if I were to set sys.argv[0:1] correctly, then I should be able to apply function.py to input.txt and store the results into output.txt.
I've already tried to define these directories, but they wouldn't work. Any help would be awesome!
your issue is that python does not know where the function directory exists. If you are trying to run a script from a sub directory like so
function
|_function.py
|
input_folder
|_input.txt
|
|output_folder
|_output.txt
you must tell python that the function folder is local, so
python ./function/function.py ./input_folder/input.txt ./output_folder/output.txt
or
python $PWD/function/function.py $PWD/input_folder/input.txt $PWD/output_folder/output.txt
$PWD is a bash variable that gives the current directory

Example cx_oracle does not work, python3.3

When I execute my file test_cx_oracle.py with a python 3.3 interpreter it errors with the following output.
**File "test_cx_oracle.py", line 3
**print con.version"**
^
SyntaxError: invalid syntax**
The contents of this file are as follows,
import cx_Oracle
con = cx_Oracle.connect('system/diamondmine#127.0.0.1/XE')
print con.version
con.close()
What does this error mean?
In python 3.x the the print statement has been replaced by a print function.
Since functions must be called by having a set of trailing () (which contain arguments to the function), you must add them to print calls in python 3.x. In the case of the print function the usual syntax is just to pass the value you wish to be printed to the print function directly.
With that in mind, changing line 3 to the following should correct your error.
print(con.version)

How to convert Balsamiq mockups to text strings txt with Python34 script on Windows XP

I've been trying to run these scripts https://github.com/balsamiq/mockups-strings-extractor within XP. I'm getting errors per this screenshot https://www.dropbox.com/s/rlbqp1iytkwvq3m/Screenshot%202014-05-30%2011.57.48.png
Also I tried CD into my test directory and although a text output file is generated it is empty and I still get these errors https://www.dropbox.com/s/odjfbr97e5i4gnn/Screenshot%202014-05-30%2012.09.31.png
Is anybody running Balsamiq on windows able to make this work ?
1) From the looks of the first error pic you included, you were trying to execute a Windows Shell command inside of a Python Interpreter. If you've still got the window open, type quit() before attempting your command again.
2) Your script was written for Python 2.x. If you're using Python 3.x, you'll need to add parentheses to the print lines in the script file and change urllib to urllib.parse. I made the changes below:
import os
import glob
import re
import urllib.parse
for infile in glob.glob( os.path.join(".", '*.bmml') ):
print("STRINGS FOUND IN " + infile)
print("===========================================================")
f = open (infile,"r")
data = f.read()
p = re.compile("<text>(.*?)</text>")
textStrings = p.findall(data)
print(urllib.parse.unquote('\n'.join(textStrings))+"\n")
f.close()
Hope this helps.

Resources