Ask Your Question
0

How to use C program directly without using files?

asked 2022-04-20 09:33:11 +0200

lijr07 gravatar image

updated 2022-04-20 09:34:15 +0200

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.

edit retag flag offensive close merge delete

Comments

Using subprocess, you can do things like:

sage: import subprocess
sage: subprocess.run(["ls", "-l"])
Sébastien gravatar imageSébastien ( 2022-04-20 13:08:32 +0200 )edit

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 ( 2022-04-20 13:10:01 +0200 )edit

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

lijr07 gravatar imagelijr07 ( 2022-04-20 14:00:20 +0200 )edit

1 Answer

Sort by » oldest newest most voted
1

answered 2022-04-20 14:15:01 +0200

Max Alekseyev gravatar image

updated 2022-04-20 14:16:57 +0200

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()
edit flag offensive delete link more

Comments

@max, thank you very much!

lijr07 gravatar imagelijr07 ( 2022-04-20 14:40:57 +0200 )edit

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: 2022-04-20 09:33:11 +0200

Seen: 43 times

Last updated: Apr 20