I trying to open and read a file with open() in python, with the global variable $USER in Linux, but the program stops in the 2 line. I want to believe that the problem is in the open() function because I use $USER in the 1 line and all is ok:
os.system("/usr/bin/nmap {target} -oN /home/$USER/.nmap_diff/scan{today}.txt")
scantxt = open("/home/$USER/.nmap_diff/scan{today}.txt","rb")
The output is:
File "diffscanner.py", line 92, in scanner
scantxt = open("/home/$USER/.nmap_diff/scan{}.txt".format(today),"rb")
FileNotFoundError: [Errno 2] No such file or directory: '/home/$USER/.nmap_diff/scan2021-07-10.txt'
The output said the scan2021-07-10.txt has not found, but it really exist: scan2021-07-10.txt
os.system
executes the command(passed as string) in a subshell. That means, the command will have access to the Linux's environment variables, USER
in your case.
On the other hand, open
expects a path-like object such as a path string. The string is read as it is and not evaluated to replace USER
(or any other environment variable) with actual values. If you want to use env var, use os.environ
import os
USER = os.environ['USER']
scantxt = open(f"/home/{USER}/.nmap_diff/scan{today}.txt","rb")