I am creating a program that will pull in a list of account numbers and then run an ls -lh
command to find a file for each one. When I run my command on our Linux server without Python it pulls up the files no problem, but then when I do it through Python it says it can't find them.
import subprocess as sp
sp.call(['cd', input_dir])
for i, e in enumerate(piv_id_list):
proc_out = sp.Popen(['ls', '-lh', '*CSV*APP*{0}.zip'.format(e)])
proc_out_list.append(proc_out)
print(proc_out)
Here is some sample output when I run the commands through the Python interpreter:
>>> ls: cannot access *CSV1000*APP*: No such file or directory
But through Linux the same command:
ls -lh *CSV*APP*
It returns the output like it should.
The subprocess. run function allows us to run a command and wait for it to finish, in contrast to Popen where we have the option to call communicate later. Talking about the code output, ls is a UNIX command that lists the files of the directory you're in.
The ls command writes to standard output the contents of each specified Directory or the name of each specified File, along with any other information you ask for with the flags. If you do not specify a File or Directory, the ls command displays the contents of the current directory.
The 'ls' command is used to list files and directories. The contents of your current working directory, which is just a technical way of stating the directory that your terminal is presently in, will be listed if you run the "ls" command without any further options.
The ls command is used to list files. "ls" on its own lists all files in the current directory except for hidden files.
This is because the shell does the replacement of wildcards with existing files that match the pattern. For example, if you have a.txt
and b.txt
, then ls *.txt
will be expanded from the shell to ls a.txt b.txt
. With your command you actually ask for ls
to return info about a file containing an asterisk in its filename. Use the following if you want to verify:
sp.Popen(['bash', '-c', 'ls', '-lh', '*CSV*APP*{0}.zip'.format(e)])
Also you should use os.chdir
to change the directory, since sp.call(['cd', input_dir])
changes the current directory for the new process you created and not the parent one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With