0

Hi all I'm new to writing in python, I'm trying work out how to parse a variable into the shell. For example;

#!/usr/python3
import os
import subprocess

sometext = 'Hello World'

os.system("echo $sometext")

This returns nothing, I'm assuming this isn't going to parse correctly. But explains what I'm trying to do.

I did some digging and have tried replacing the last line

#!/usr/python3
import os
import subprocess

sometext = 'Hello World'

subprocess.call('echo {sometext}')

this spits the following error;

Shell % python3 pingtest.py
Traceback (most recent call last):
  File "pingtest.py", line 12, in <module>
    subprocess.call('echo {sometext}')
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 340, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1702, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'echo {sometext}'
Jewson
  • 3
  • 2
  • An unobvious complication is that without `shell=True`, Python will look for an executable whose name is literally `'echo {sometext}'`. If you really need `shell=True`, add it; but for most tasks, you [probably want to avoid it if you can.](/questions/3172470/actual-meaning-of-shell-true-in-subprocess) – tripleee Dec 03 '20 at 21:27

1 Answers1

0
#!/usr/bin/python3
import subprocess
sometext = 'Hello World'
subprocess.call(["echo", sometext])
tripleee
  • 175,061
  • 34
  • 275
  • 318
Avihay Tsayeg
  • 444
  • 4
  • 10