Меню

Unexpected token python ошибка

I am a Python Novice so please help me out…

#!/usr/bin/python -tt

import sys
import commands

def runCommands():
  f = open("a.txt", 'r')
  for line in f:  # goes through a text file line by line
    cmd = 'ls -l ' + line 
    print "printing cmd = " + cmd,
    (status, output) = commands.getstatusoutput(cmd)
  if status:    ## Error case, print the command's output to stderr and exit
      print "error"
      sys.stderr.write(output)
      sys.exit(1)
  print output
  f.close()

def main():
  runCommands()

# Standard boilerplate at end of file to call main() function.
if __name__ == '__main__':
  main()

I run it as follows:

$python demo.py
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error

Running less $(which python) says:

#!/bin/sh bin=$(cd $(/usr/bin/dirname "$0") && pwd) exec -a "$0" "$bin/python2.5" "$@"

If i remove for loop then it works fine

$cat a.txt
dummyFile


$ls -l dummyFile
-rw-r--r-- 1 blah blah ...................

$python demo.py
printing cmd = ls -l dummyFile
sh: -c: line 1: syntax error near unexpected token `;'
sh: -c: line 1: `; } 2>&1'
error

I am using ‘ls’ just for showing the problem. Actually i wanna use some internal shell scripts so i have to run this python script in this way only.

asked Jun 5, 2012 at 15:54

rajya vardhan's user avatar

rajya vardhanrajya vardhan

1,1114 gold badges16 silver badges29 bronze badges

4

The problem is caused by this line:

    cmd = 'ls -l ' + line

it should be modified to:

    cmd = 'ls -l ' + line.strip() 

When you read the line from your text file, you also read the trailing n. You need to strip this so that it works. The getstatusoutput() doesn’t like the trailing newline. See this interactive test (which is how I verified it):

In [7]: s, o = commands.getstatusoutput('ls -l dummyFile')

In [8]: s, o = commands.getstatusoutput('ls -l dummyFilen')
sh: Syntax error: ";" unexpected

answered Jun 5, 2012 at 15:59

Levon's user avatar

LevonLevon

135k33 gold badges198 silver badges187 bronze badges

2

This seems to be a problem with the «python» command, perhaps it’s a shell wrapper script or something.

Run

$ less $(which python)

UPDATE:

Try calling the Python executable directly, it seems to be at /usr/bin/python2.5:

$ /usr/bin/python2.5 demo.py

answered Jun 5, 2012 at 15:56

unwind's user avatar

unwindunwind

387k64 gold badges467 silver badges600 bronze badges

3

The documentation for the commands module states that when you run getstatusoutput(cmd),

cmd is actually run as { cmd ; } 2>&1

This should explain where the ; } 2>&1 is coming from.

My first guess is that the problem is being caused by not stripping the newlines off the end of each line you read from the file, and so the command you’re actually running is something like

{ ls -l somedir
; } 2>&1

However, I don’t know shell programming very well so I don’t know how sh will cope with the contents of the { ... } split over two lines, nor why it reports the problem on line 1 when there are now two lines.

A second guess is that there’s a blank line in your file, in which case sh may be complaining because it’s looking for an argument for ls and it found ; } 2>&1 instead.

A third guess is that one of the files contains a }, or maybe a ; followed by a }.

Ultimately, I can’t say for sure what the problem is without seeing the contents of your file a.txt.

Incidentally, I hope this file doesn’t contain a line / && sudo rm -rf /, as that might cause you one or two problems.

answered Jun 5, 2012 at 16:45

Luke Woodward's user avatar

Luke WoodwardLuke Woodward

62k16 gold badges88 silver badges104 bronze badges

Got this answer from somewhere else:

When you iterate through a file as an iterator, newlines are NOT stripped. The following is ACTUALLY what your script is executing. The fact that you have a trailing comma on your print statement (and a newline on your output) is the giveaway.

ls -l dummyFile n

Which commands interprets as

{ ls -l dummyFile
; } 2>&1

Call line.rstrip() (or just strip) to fix it.

cmd = 'ls -l ' + line.strip()

answered Jun 5, 2012 at 17:00

rajya vardhan's user avatar

rajya vardhanrajya vardhan

1,1114 gold badges16 silver badges29 bronze badges

triatri3

11 / 12 / 8

Регистрация: 16.11.2016

Сообщений: 892

1

07.01.2019, 20:14. Показов 15420. Ответов 5

Метки нет (Все метки)


Python
1
2
3
4
5
6
7
8
9
10
11
a1 = '    _~_    '
a2 = '   (o o)   '
a3 = '  /  V    '
a4 = ' /(  _  ) '
a5 = '   ^^ ^^   '
 
print(a1*v)
print(a2*v)
print(a3*v)
print(a4*v)
print(a5*v)

Ошибки в строках 2 и 3: unexpected token ‘<newline>’
13: unexpected token ‘<dedent>’
14:unexpected token ‘else’
15: unexpected indent.
Я лишь начинаю изучение языка, не могли бы подсказать где ошибка?

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

07.01.2019, 20:14

5

Catstail

Модератор

Эксперт функциональных языков программированияЭксперт Python

33778 / 18815 / 3968

Регистрация: 12.02.2012

Сообщений: 31,559

Записей в блоге: 12

07.01.2019, 21:38

2

Найди одно отличие:

Python
1
2
3
4
5
6
7
8
9
10
11
a1 = '    _~_    '
a2 = '   (o o)   '
a3 = '  /  V    '
a4 = ' /(  _  ) '
a5 = '   ^^ ^^   '
v=3
print(a1*v)
print(a2*v)
print(a3*v)
print(a4*v)
print(a5*v)

https://ideone.com/ZmmZdQ



0



triatri3

11 / 12 / 8

Регистрация: 16.11.2016

Сообщений: 892

08.01.2019, 12:07

 [ТС]

3

Извините, не то вставил. Вот полный код

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
value=int(input())
if (value>0 and value<10)
    a1 = '    _~_    '
    a2 = '   (o o)   '
    a3 = '  /  V    '
    a4 = ' /(  _  ) '
    a5 = '   ^^ ^^   '
 
    print(a1*v)
    print(a2*v)
    print(a3*v)
    print(a4*v)
    print(a5*v)
else
    print ("Error!")

Цитата
Сообщение от Catstail
Посмотреть сообщение

Найди одно отличие:

Да, я взял готовый код откуда-то на этом форуме. Возможно у Вас. Не разрешаете его использовать?



0



Модератор

Эксперт функциональных языков программированияЭксперт Python

33778 / 18815 / 3968

Регистрация: 12.02.2012

Сообщений: 31,559

Записей в блоге: 12

08.01.2019, 12:15

4

Лучший ответ Сообщение было отмечено triatri3 как решение

Решение

А этот код содержит две ошибки и не запустится. Подсказать, или сам найдешь?



0



Просто Лис

Эксперт Python

4798 / 3125 / 986

Регистрация: 17.05.2012

Сообщений: 9,136

Записей в блоге: 9

08.01.2019, 13:43

5

Лучший ответ Сообщение было отмечено triatri3 как решение

Решение

Я подскажу. Пропущено два двоеточия.

Добавлено через 30 секунд
И переменной v не существует.



1



Dax

Модератор

Эксперт Python

1351 / 648 / 207

Регистрация: 23.03.2014

Сообщений: 3,051

09.01.2019, 11:07

6

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def pin():
    p = int(input("сколько нарисовать?"))
    if (p > 0 and p < 10):
        a1 = '    _~_    '
        a2 = '   (o o)   '
        a3 = '  /  V    '
        a4 = ' /(  _  ) '
        a5 = '   ^^ ^^   '
 
        print(a1 * p)
        print(a2 * p)
        print(a3 * p)
        print(a4 * p)
        print(a5 * p)
    else:
        print("Error!")
if __name__ == '__main__':
    pin()



0



  1. Error: bash: syntax error near unexpected token '(' in Python
  2. Fix Error: bash: syntax error near unexpected token '(' in Python

Error: Bash: Syntax Error Near Unexpected Token '(' in Python

Every time a Python code runs through a shell terminal such as Bash, it must point to an interpreter. If Bash cannot find a suitable way to run the file, then it will give out errors.

This guide will discuss Error: Bash: syntax error near unexpected token '('.

Error: bash: syntax error near unexpected token '(' in Python

Python needs to be installed on your computer for the interpreter to find and run the Python files. The interpreter works differently in different operating systems.

In Windows, when we install Python, a program called IDLE is installed on the computer, which comes with the interpreter. It runs Python codes.

In Linux, we can access Python using the shell terminal by typing the command python. It opens the Python environment where the code can be written and run.

If the code has trouble finding the Python interpreter, it will run on whichever shell it runs. If the user runs the code from the Bash terminal, then the shell will give an error that will resemble this:

#Python 3.x
Error: bash: syntax error near unexpected token '('

Bash is a Unix command and is the default shell for most Linux distributions. It cannot understand Python code, so it gives out this error.

It might not give an error on the first line of the code and will give the error later because it might interpret some of the code as a shell command.

Fix Error: bash: syntax error near unexpected token '(' in Python

There are multiple ways to fix this error in Python. The fixes vary between Linux and Windows because these operating systems work differently.

Solutions for Linux

The path to the interpreter should be added to the code file so that the computer knows the interpreter has to run this file and not the shell terminal. We should add the following line at the top of the code file:

#Python 3.x
#!/usr/bin/env python

It runs the file from the Python interpreter, not the Bash shell. We have to note that this is not a Python comment.

Instead, this shell command starts the Python environment in the shell before running the code. The user can also run the code file on the shell by giving the python command before the file name, like python filename.py.

It also does the same and runs the file from the Python interpreter. If we have both Python 2 and 3 installed, we need to write python3 if we want to run the code using Python 3. And just python if we want to run the code using Python 2.

Example Code:

#Python 3.x
#!/usr/bin/env python
print("Hello World")

Output:

Solution for Windows

In Windows, the user can also use the python keyword in the terminal to run the code file, but before doing so, the path to the Python interpreter needs to add to the PATH variable of Windows. The steps to do that are:

  1. Search for env in the Windows search bar and open the Edit the system environment variables option.
  2. Now open the Environment Variables.
  3. Now, choose the PATH variable and click on Edit.
  4. Paste the interpreter’s path in an empty field in this window.
  5. The path to the interpreter is now added to the user’s Windows, and we can use the python command to run the code files from the shell.

Now we need to write the following in a terminal to run the code:

#Python 3.x
python filename.py

While running the simple Python program below, I’m getting the following error:

./url_test.py: line 2: syntax error near unexpected token `('                  
./url_test.py: line 2: `response = urllib2.urlopen('http://python.org/')'

import urllib2      
response = urllib2.urlopen('http://python.org/')  
print "Response:", response

# Get the URL. This gets the real URL. 
print "The URL is: ", response.geturl()

# Getting the code
print "This gets the code: ", response.code

# Get the Headers. 
# This returns a dictionary-like object that describes the page fetched, 
# particularly the headers sent by the server
print "The Headers are: ", response.info()

# Get the date part of the header
print "The Date is: ", response.info()['date']

# Get the server part of the header
print "The Server is: ", response.info()['server']

# Get all data
html = response.read()
print "Get all data: ", html

# Get only the length
print "Get the length :", len(html)

# Showing that the file object is iterable
for line in response:
 print line.rstrip()

# Note that the rstrip strips the trailing newlines and carriage returns before
# printing the output.

We all get errors — no big deal! Here are some errors you’re likely to encounter.

The Python Script node often gives useful feedback when things go wrong, enabling us to figure out where the problems in our code lie.

Since most errors begin with: ‘IronPythonEvaluator.EvaluateIronPythonScript operation Failed‘, this will be omitted from any errors below.

Traceback errors try and tell the full story of errors as they happened. As with Dynamo, an error somewhere is likely to cause a cascade of errors to occur. The Traceback message will tell you where things went wrong in reverse order, telling you the source of the error first with its line number.

It will also often give information as to the kind of error, such as ‘TypeError’. From the kinds of errors, it is possible to further infer what went wrong in your code.

The referenced object is not valid, possibly because it has been deleted from the database, or its creation was undone

This is a common error, which translates to ‘your script tried to refer to an object that is no longer there’. This is most often caused by deleting an element from the active document and then trying to access that element again after its deletion.

This is simply down to a syntax error (your fault, I’m afraid). Perhaps you forgot the ‘:’ after a conditional branch or there is an unclosed parenthesis left somewhere in your code?

Python scripts are broken down into ‘tokens’ which helps the program navigate the logic of your code. If the parser comes across a token which makes no sense in the Python language, your node will throw this error.

‘Unexpected Indent’ or ‘Inconsistent Use of Tabs and Spaces’

The in-built Python Script editor often has troubles with tabs and spaces in larger scripts. These can be especially tricky to remedy as they’re invisible! Fortunately, this can be easily resolved by using Microsoft’s Visual Studio Code application.

First, you’ll need to get it set up:

  1. 2.

    Once installed, you’ll need to install the Python extension and pylint.

  2. 3.

    Start a new file, make sure it’s read as a Python file.

  3. 4.

    In the View menu, select ‘Command Palette’ and type ‘Convert Indentation to Tabs’.

That’s it — you should now be able to copy/paste your code back into the Dynamo Python Editor window.

Modifying is forbidden because the document has no open transaction.

Thanks for the responses. I thought about it a bit and decided to look for a python-native way to do it. There was enough information at the python cryptography cheatsheet website and others that I was able to put together the python code to generate the CSR.

requires pyOpenSSL


from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend())

with open('mycert.key', 'wb') as f:
     f.write(key.private_bytes(
     encoding=serialization.Encoding.PEM,
     format=serialization.PrivateFormat.TraditionalOpenSSL,
     encryption_algorithm=serialization.NoEncryption()))

from OpenSSL import crypto

# load private key
ftype = crypto.FILETYPE_PEM
with open('mycert.key', 'rb') as f: key = f.read()
key = crypto.load_privatekey(ftype, key)
req    = crypto.X509Req()

alt_name  = [ b"DNS:mynode",
              b"DNS:myF5",
              b"email:administratore@email.com" ]
key_usage = [ b"Digital Signature",
              b"Key Encipherment" ]
key_usage = [ b"digitalSignature",
              b"keyEncipherment" ]
ext_key_usage = [ b"serverAuth",
                  b"clientAuth" ]

# country (countryName, C)
# state or province name (stateOrProvinceName, ST)
# locality (locality, L)
# organization (organizationName, O)
# organizational unit (organizationalUnitName, OU)
# common name (commonName, CN)

req.get_subject().C  = "US"
req.get_subject().ST = "Florida"
req.get_subject().L  = "St Petersburg"
req.get_subject().O  = "myCompany"
req.get_subject().OU = "MyOU"
req.get_subject().CN = "mynode"
req.add_extensions([
    crypto.X509Extension( b"basicConstraints",
                          False,
                          b"CA:FALSE"),
    crypto.X509Extension( b"keyUsage",
                          False,
                          b",".join(key_usage)),
    crypto.X509Extension( b"subjectAltName",
                          False,
                          b",".join(alt_name))
])

req.set_pubkey(key)
req.sign(key, "sha256")

csr = crypto.dump_certificate_request(ftype, req)
with open("mycert.csr", 'wb') as f: f.write(csr)

I’m getting the issue as well. I believe I’m using the new language server, but don’t have a way to check. I’m also getting like 10 other parsing errors that are also false alarms, but I can open a new issue for those if desired.

image

The code for the above problems is hangouts_parser.py from er0sin/hangouts_to_sms

For people who use text search, I’ll copy the issues below:

Below are the json error reports:

The Error Reports

{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "invalid syntax",
	"source": "Python (parser)",
	"startLineNumber": 10,
	"startColumn": 61,
	"endLineNumber": 10,
	"endColumn": 64
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "unexpected token 'open'",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 14,
	"endLineNumber": 25,
	"endColumn": 18
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E80",
	"severity": 8,
	"message": "can't assign to literal",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 18,
	"endLineNumber": 25,
	"endColumn": 53
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "unexpected token '='",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 53,
	"endLineNumber": 25,
	"endColumn": 54
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "unexpected token ')'",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 61,
	"endLineNumber": 25,
	"endColumn": 62
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "unexpected token 'data_file'",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 66,
	"endLineNumber": 25,
	"endColumn": 75
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "unexpected token ':'",
	"source": "Python (parser)",
	"startLineNumber": 25,
	"startColumn": 75,
	"endLineNumber": 25,
	"endColumn": 76
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E32",
	"severity": 8,
	"message": "unexpected indent",
	"source": "Python (parser)",
	"startLineNumber": 27,
	"startColumn": 13,
	"endLineNumber": 27,
	"endColumn": 17
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E80",
	"severity": 8,
	"message": "can't assign to ErrorExpression",
	"source": "Python (parser)",
	"startLineNumber": 27,
	"startColumn": 13,
	"endLineNumber": 27,
	"endColumn": 17
}
{
	"resource": "/c:/Users/USERNAME/odrive/Google Drive/Random/Hangouts2Messages-SMS/hangouts_to_sms_er0sin/hangouts_parser.py",
	"owner": "_generated_diagnostic_collection_name_#0",
	"code": "E16",
	"severity": 8,
	"message": "'return' outside function",
	"source": "Python (parser)",
	"startLineNumber": 65,
	"startColumn": 9,
	"endLineNumber": 65,
	"endColumn": 15
}

Edit: Possibly important detail, the «Analyzing workspace, 8 items remaining» is taking it’s sweet time (about an hour at this point) of finishing it’s analysis. I have some quite large json files (300+MB) which it might be hanging on.

image

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Unrar dll вернул код ошибки 12
  • Unexpected token else javascript ошибка