First time here? Check out the FAQ!

Ask Your Question
0

How to use C program directly without using files?

asked 3 years ago

lijr07 gravatar image

updated 3 years ago

I would like to use C program in SageMath. The way I do it is as follows:

    fp1='r4.txt'
    fp2='commandToRunC.txt'
    fp3='HL8results18.txt'
    F1 = open(fp1,'w')
    for j in p1:
        F1.write(chr(j+48))
    F1.write(str(' '))
    for j in p2:
        F1.write(str(j))
    F1.write(str('\n'))
    F1.close()

    F1 = open(fp2,'w')
    F1.write("./a.out ")
    F1.write(str(kk))
    F1.write(" r4.txt | awk '{print $NF}' > HL8results18.txt")
    F1.close()

    import os
    with open(fp2, 'r') as fp:
        L = fp.readline()
    cmd = L
    os.system(cmd)

This works but I need to rewrite the data in txt files r4.txt, commandToRunC.txt, HL8results18.txt each time. The computation I am doing is quite large. So I would like to not to write the results to files but use them directly in SageMath. Is there some way to do this? Thank you very much.

Preview: (hide)

Comments

Using subprocess, you can do things like:

sage: import subprocess
sage: subprocess.run(["ls", "-l"])
Sébastien gravatar imageSébastien ( 3 years ago )

Why do you create the file fp2? You may just create the list of commands L yourself in the script.

Sébastien gravatar imageSébastien ( 3 years ago )

@Sebastien, thank you very much! I will try your suggestions.

lijr07 gravatar imagelijr07 ( 3 years ago )

1 Answer

Sort by » oldest newest most voted
1

answered 3 years ago

Max Alekseyev gravatar image

updated 3 years ago

You cannot avoid creating r4.txt if C program wants its input in the file (unless you modify the program). The other files can be eliminated via:

import os
result = os.popen(f"./a.out {kk} r4.txt | awk '{{print $NF}}'").read()
Preview: (hide)
link

Comments

@max, thank you very much!

lijr07 gravatar imagelijr07 ( 3 years ago )

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 3 years ago

Seen: 219 times

Last updated: Apr 20 '22