1

I'm trying to run a bash-command in python where the bash-command saves data to a file rather than displaying it. An example of such command is

$ echo 'foo' > bar.txt

currently my code looks like the following

process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
process.communicate()

As I run the python-code no bar.txt is generated. Any idea on how to save the data from the bash-script? The data should not be displayed only saved.

2
  • 2
    Redirection using > and shell-builtins like echo, require bash. So add shell=True to your Popen. Commented Jul 5, 2016 at 14:50
  • 2
    There is no point passing a stdout argument if you redirect the commands output with >. Commented Jul 5, 2016 at 14:53

2 Answers 2

1

By default, subprocess.Popen() does not run the command via the shell, and therefore I/O redirection operators have no special meaning -- they are treated as ordinary arguments. The easiest way to achieve what you're after is to make it use the shell. With Popen(), you would pass shell=True, and you would not split the command string:

process = subprocess.Popen(bashCommand, stdout=subprocess.PIPE, shell=True)

You should also consider whether the subprocess.call() (Python 2) or subprocess.run() (Python 3) convenience functions offer any advantage to you. It's not clear whether they do, however; in particular, you would need to use the same shell argument in both those cases as well.

Sign up to request clarification or add additional context in comments.

Comments

0

Use print(). Simple as that. Anything that would normally be printed to the console will instead be printed to a file, because of the > command.

~$ python3.5 your_script.py > bar.txt

If you do not want to run your python script with >, then you will need to use python’s file operations to write a string version of your data to a file:

with open('bar.txt', 'w') as F: 
    F.write(data)

2 Comments

Unfortunately that option is not available as other prints need to be displayed for user-action
Then you need to assign the output as a string in python, and use with open(filename, 'w') as F: F.write(string) to write to a file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.