0

I read through a lot of the answers but can't figure out how to execute a command which I currently execute using cron from subprocess or something better?

# cron command
00 16 * * 1-5 DISPLAY=:10 /path/to/shell/script.sh > log/file.log 2>&1

The DISPLAY is Xvfb.

3
  • 1
    Use os.env to set the environment variable, then use subprocess.Popen() to run the script. Commented Nov 8, 2022 at 16:24
  • @Barmar how would I go about doing that? The DISPLAY=:10 is initiated. I tried checking os.env() but got a >AttributeError: module 'os' has no attribute 'env' Commented Nov 8, 2022 at 16:29
  • 2
    Sorry, it's os.environ. So os.environ['DISPLAY'] = ':10' Commented Nov 8, 2022 at 16:29

2 Answers 2

1

Set the environment variable using os.environ, then run the command using the subprocess module.

import subprocess
import os

os.environ['DISPLAY'] = ':10'
with open('log/file.log') as out:
    subprocess.Popen(['/path/to/shell/script.sh'], stdout=out, stderr=subprocess.STDOUT)
Sign up to request clarification or add additional context in comments.

3 Comments

That's true, but unless the Python script is using the DISPLAY environment variable for other things, it probably doesn't matter.
There are mutliple scripts being run using cron which are utilizing the DISPLAY. I am not sure if this affects the code though. I am getting a >Error: process is already running.
That's an unrelated issue. If script.sh only allows itself to be run once, you can't run it from both cron and from your Python script at the same time. It has nothing to do with DISPLAY.
0

Using the env= argument to subprocess.Popen, you can change the environment only for the child process, without modifying the environment of the Python process itself:

import subprocess
import os

with open('log/file.log') as out:
    subprocess.Popen(['/path/to/shell/script.sh'],
                     env=dict(os.environ, DISPLAY=":10"),
                     stdout=out, stderr=subprocess.STDOUT)

4 Comments

I get an TypeError: unsupported operand type(s) for |: 'dict' and 'dict'. Its from the env=(dict(os.environ) | {"DISPLAY": ":10"}) trying to fix it.
Which version of Python? Works fine on 3.9
Oh, I am using: 3.6.9
@Sid, how about env=dict(os.environ, DISPLAY=":10")?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.