Python Forum

Full Version: using a shell script within python
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to use a C-shell script within a python program, which works with two arguments.

os.system("recall 20170121 ../E725.txt xy 1")

But I want to use it for a stack, so declared the variables like below, but when I call them within the script it gives an error, that the input file doesn' exist. How can I call the variables?

date_ID=(filename[17:25])
fullpath = '../%s' % (filename)
os.system("import_S1_TOPS_modified $date_ID $fullpath vv 1")
(Oct-10-2018, 09:26 AM)Krszt Wrote: [ -> ]I want to use a C-shell script within a python program, which works with two arguments.

os.system("recall 20170121 ../E725.txt xy 1")

But I want to use it for a stack, so declared the variables like below, but when I call them within the script it gives an error, that the input file doesn' exist. How can I call the variables?

date_ID=(filename[17:25])
fullpath = '../%s' % (filename)
os.system("import_S1_TOPS_modified $date_ID $fullpath vv 1")

As far as Python interpreter is concerned, $date_ID and $fullpath in your command line are just string literals within a string. In order to place values within the command string
  • If you are using version >= 3.6 - modify your string as
    f"import_S1_TOPS_modified ${date_ID} ${fullpath} vv 1"
  • if not
    "import_S1_TOPS_modified ${} ${} vv 1".format(date_ID, fullpath)
Should not be using os.system(),subprocess replace it a better/safer way.
Ideally is better/safer to pass in a list.
import subprocess

subprocess.run(['ls', '-l'])
Passing in a string has to use shell=True
import subprocess

subprocess.run('ls -l', shell=True)
So as shown bye @volcano63 can pass in using f-string or format(),
but the method with list when shell=False is advisable.
import subprocess

arg = '-l'
subprocess.run(f'ls {arg}', shell=True)
The subprocess has a lot stuff that make it better,even run(that replace call) can now also catch output.
import subprocess

out = subprocess.run(['ls', '-l'], capture_output=True)
print(out.stdout.decode())