Home > Blockchain >  Subprocess to pass variable and replacing a variable
Subprocess to pass variable and replacing a variable

Time:01-14

I am trying to use this command:

import subprocess
a = 'foo'
result = subprocess.check_output(["cal | awk '{ gsub($1, $a); print $cal}'", "-l"], 
                                 shell=True)

My intention is to change the first column of the cal variable with my own variable, a already has the same type as $1, but I'm struggling to print a new calendar with my own entries in certain places.

If this is a bad idea, I'm looking at how to change certain days to some other characters in the cal command.

CodePudding user response:

Not exactly sure where do you want to print that new calendar but I found few problems with your shell command

  1. Variables inside ' ' doesn't evaluate. You need to use " "
  2. I guess you expect to take a from python script, not shell env variable. To populate it you can use f-strings.
  3. To replace string in text, I would rather use sed.

Solution:

import subprocess

python_var = "foo"
result = subprocess.check_output(f'cal | sed "s/$shell_var/{python_var}/"', shell=True)
print(result)
$ export shell_var=mo
$ python script.py # it prints new result variable that contains new calendar.
  •  Tags:  
  • Related