0

I have a python script and want to call a subprocess from it. The following example works completely fine:

Script1:

from subprocess import Popen

p = Popen('python Script2.py', shell=True)

Script2:

def execute():
    print('works!')

execute()

However as soon as I want to pass a variable to the function, I get the following error:

def execute(random_variable: str):

SyntaxError: invalid syntax

Script1:

from subprocess import Popen 

p = Popen('python Script2.py', shell=True)

Script2:

def execute(random_variable: str):
    print(random_variable)

execute(random_variable='does not work')

Does anyone have an idea why that could be the case? Couldn't find anything about it online :(

Sanjay
  • 1,958
  • 2
  • 17
  • 25
Luis
  • 17
  • 6
  • 2
    which python version are you using? – Sanjay Feb 18 '20 at 17:14
  • 1
    When you're on a unix-like system, `python` on the command line might link to python2, which does not know type hints. – Talon Feb 18 '20 at 17:16
  • i'm using python 3.8 on a mac, with pycharm – Luis Feb 18 '20 at 17:20
  • are you running this inside virtualenv? if yes then check which python is there inside virtualenv – Sanjay Feb 18 '20 at 17:25
  • Are you sure this is the correct syntax for the type hint? The examples at https://docs.python.org/3/library/typing.html imply you should also be defining the output type of execute. Have you tried it _without_ using a type hint at all? – Sarah Messer Feb 18 '20 at 17:27
  • no, not running in a virtualenv – Luis Feb 18 '20 at 17:32
  • actually, if I remove the type hint it seems to work fine, no Idea why.... but gonna test this first – Luis Feb 18 '20 at 17:33
  • If it works fine without the type hint, chances are good the type hint is at least contributing to the problem. Have you tried specifying the output type of execute(), as shown on the page I linked above? – Sarah Messer Feb 18 '20 at 18:21

2 Answers2

0

Python type hint is introduced in python3.5. if you run this with less than version python3.5 then it will throw this error.

    def execute(random_variable: str):
                               ^
SyntaxError: invalid syntax

thats why first script worked and later one failed.

Sanjay
  • 1,958
  • 2
  • 17
  • 25
  • alright, but actually I'm using ```python 3.8```... what could I do then to make it work? – Luis Feb 18 '20 at 17:24
  • when you create a project in pycharm it creates virtualenv, if you have a virtualenv can you make sure the correct python version? – Sanjay Feb 18 '20 at 17:31
0

ok guys, found the solution: just use 'python3' instead of 'python' if you are on mac...:

p = Popen('python3 Script2.py', shell=True)

Thank you for your helpfulness! :)

Luis
  • 17
  • 6